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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. background-color: #999;
  19. margin:100px auto;
  20. }
  21. .box ul{
  22. display: flex;
  23. }
  24. .box li{
  25. width: 200px;
  26. height: 100px;
  27. font-size: 50px;
  28. font-weight: bold;
  29. text-align: center;
  30. line-height: 100px;
  31. color: white;
  32. }
  33. .box ul .active{
  34. background-color: #111;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <div class="box">
  40. <ul>
  41. <li class="active">first</li>
  42. <li>second</li>
  43. <li>thrid</li>
  44. </ul>
  45. </div>
  46. <script>
  47. var lis = document.querySelectorAll("li");
  48. // 循环绑定事件
  49. for(var i=0;i<lis.length;i++){
  50. lis[i].onclick = function(){
  51. // 点击li时,移除所有active类名
  52. for(var j=0;j<lis.length;j++){
  53. lis[j].classList.remove("active");
  54. }
  55. // 点击li时,为当前li添加active类名
  56. this.classList.add("active");
  57. // 使用hash模式添加历史记录
  58. location.hash = this.innerText;
  59. }
  60. }
  61. // 监听hashchange事件
  62. window.onhashchange = function(){
  63. // 获取当前hash值
  64. var hash = location.hash;
  65. // 截取字符串#后面的内容
  66. hash = hash.substring(1);
  67. console.log(hash);
  68. // 根据hash值,切换active类名
  69. for(var i=0;i<lis.length;i++){
  70. if(lis[i].innerText == hash){
  71. lis[i].classList.add("active");
  72. }else{
  73. lis[i].classList.remove("active");
  74. }
  75. }
  76. }
  77. </script>
  78. </body>
  79. </html>