练习3_hash历史管理.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. * {
  9. margin: 0;
  10. padding: 0;
  11. }
  12. li {
  13. list-style: none;
  14. }
  15. .box {
  16. width: 600px;
  17. height: 100px;
  18. margin: 100px auto;
  19. }
  20. .box ul {
  21. display: flex;
  22. }
  23. .box li {
  24. width: 200px;
  25. height: 100px;
  26. background-color: #aaa;
  27. font-size: 50px;
  28. text-align: center;
  29. line-height: 100px;
  30. color: #fff;
  31. }
  32. .box .active {
  33. background-color: #111;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <div class="box">
  39. <ul>
  40. <li class="first active">first</li>
  41. <li class="second">second</li>
  42. <li class="third">third</li>
  43. </ul>
  44. </div>
  45. <script>
  46. var aLi = document.querySelectorAll("li");
  47. for (var i = 0; i < aLi.length; i++) {
  48. aLi[i].onclick = function () {
  49. var innerText = this.innerText;
  50. window.location.hash = innerText;
  51. for (var j = 0; j < aLi.length; j++) {
  52. aLi[j].classList.remove("active");
  53. }
  54. this.classList.add("active");
  55. }
  56. }
  57. window.onhashchange = function(){
  58. var hash = window.location.hash;
  59. hash = hash.slice(1);
  60. console.log(hash);
  61. if(hash == ""){
  62. for(var j=0;j<aLi.length;j++){
  63. aLi[j].classList.remove("active");
  64. }
  65. aLi[0].classList.add("active");
  66. return;
  67. }
  68. for(var i=0;i<aLi.length;i++){
  69. if(aLi[i].innerText == hash){
  70. aLi[i].classList.add("active");
  71. }else{
  72. aLi[i].classList.remove("active");
  73. }
  74. }
  75. }
  76. </script>
  77. </body>
  78. </html>