练习3_历史管理hash.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. .box div{
  9. width: 200px;
  10. height: 120px;
  11. background-color: #aaa;
  12. color: #fff;
  13. font-size: 40px;
  14. font-weight: bolder;
  15. text-align: center;
  16. line-height: 120px;
  17. }
  18. .box{
  19. display: flex;
  20. }
  21. .box .active{
  22. background-color: #111;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div class="box">
  28. <div class="tab-btn active">first</div>
  29. <div class="tab-btn">second</div>
  30. <div class="tab-btn">third</div>
  31. </div>
  32. <script>
  33. let tabBtns = document.querySelectorAll('.tab-btn');
  34. let hashArr = ["first","second","third"];
  35. tabBtns.forEach((item,index)=>{
  36. item.onclick = function(){
  37. // 管理选中状态
  38. // tabBtns.forEach((item)=>{
  39. // item.classList.remove("active");
  40. // });
  41. // this.classList.add("active");
  42. // 管理hash
  43. location.hash = hashArr[index]
  44. }
  45. })
  46. // 监听hash变化
  47. window.onhashchange = function(){
  48. // 获取hash值
  49. let hashVal = location.hash.slice(1);
  50. // 根据hash值,管理选中状态
  51. // 获取hash值对应的索引
  52. // let index = hashArr.indexOf(hashVal);
  53. let index = hashArr.findIndex((item)=>{
  54. // if(item == hashVal){
  55. // return true;
  56. // }
  57. return item == hashVal;
  58. })
  59. tabBtns.forEach((item)=>{
  60. item.classList.remove("active");
  61. });
  62. tabBtns[index].classList.add("active");
  63. }
  64. </script>
  65. </body>
  66. </html>