练习4_历史管理hash.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. ul {
  16. display: flex;
  17. }
  18. li {
  19. width: 200px;
  20. height: 100px;
  21. color: white;
  22. background-color: gray;
  23. line-height: 100px;
  24. text-align: center;
  25. font-size: 40px;
  26. font-weight: bold;
  27. }
  28. .active {
  29. background-color: black;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <!-- 第一步实现样式 -->
  35. <div>
  36. <ul>
  37. <li class="active">first</li>
  38. <li>second</li>
  39. <li>third</li>
  40. </ul>
  41. </div>
  42. <script>
  43. // 第二步绑定事件
  44. // 获取元素
  45. var aLi = document.querySelectorAll("li");
  46. // 循环绑定事件
  47. for (var i = 0; i < aLi.length; i++) {
  48. aLi[i].onclick = function () {
  49. // 移除所有选中状态
  50. for (var j = 0; j < aLi.length; j++) {
  51. aLi[j].classList.remove("active");
  52. }
  53. // 添加类名
  54. this.classList.add("active");
  55. // 修改hash值增加历史记录
  56. location.hash = this.innerText;
  57. }
  58. }
  59. // 第三步监听hash值变化
  60. window.onhashchange = function () {
  61. // 获取hash值
  62. var hash = location.hash;
  63. // 去掉#
  64. hash = hash.substr(1);
  65. // 移除所有选中状态
  66. for (var j = 0; j < aLi.length; j++) {
  67. aLi[j].classList.remove("active");
  68. }
  69. // 循环查找对应的hash值
  70. for (var i = 0; i < aLi.length; i++) {
  71. if (hash == aLi[i].innerText) {
  72. // 添加类名
  73. aLi[i].classList.add("active");
  74. }
  75. }
  76. }
  77. </script>
  78. </body>
  79. </html>