练习题4_历史管理2.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. ul{
  9. margin: 0;
  10. padding: 0;
  11. display: flex;
  12. }
  13. li{
  14. list-style: none;
  15. width: 100px;
  16. height: 50px;
  17. background-color: #aaa;
  18. color: #fff;
  19. font-weight: bold;
  20. text-align: center;
  21. line-height: 50px;
  22. }
  23. .active{
  24. background-color: #000;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <ul>
  30. <li data-hash="first" class="active">first</li>
  31. <li data-hash="second">second</li>
  32. <li data-hash="third">third</li>
  33. </ul>
  34. <script>
  35. let aLi = document.querySelectorAll("li");
  36. for(let i=0;i<aLi.length;i++){
  37. aLi[i].onclick = function(e){
  38. let thisVal = e.target.dataset.hash;
  39. // location.hash = thisVal;
  40. history.pushState(thisVal,"");
  41. for(let j=0;j<aLi.length;j++){
  42. aLi[j].classList.remove("active");
  43. }
  44. this.classList.add("active");
  45. }
  46. }
  47. window.onpopstate = function(e){
  48. console.log(e.state);
  49. for(let i=0;i<aLi.length;i++){
  50. if(aLi[i].dataset.hash == e.state){
  51. aLi[i].classList.add("active")
  52. }else{
  53. aLi[i].classList.remove("active");
  54. }
  55. }
  56. }
  57. </script>
  58. </body>
  59. </html>