练习题4_history历史管理.html 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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" data-id="1001">first</li>
  42. <li data-id="1002">second</li>
  43. <li data-id="1003">thrid</li>
  44. </ul>
  45. </div>
  46. <script>
  47. // 获取元素
  48. var lis = document.querySelectorAll("li");
  49. // 循环绑定事件
  50. for(var i=0;i<lis.length;i++){
  51. lis[i].onclick = function(){
  52. for(var j=0;j<lis.length;j++){
  53. lis[j].classList.remove("active");
  54. }
  55. this.classList.add("active");
  56. // 使用history模式添加历史记录
  57. console.log(this);
  58. var thisId = this.dataset.id;
  59. history.pushState(thisId,"");
  60. }
  61. }
  62. // 监听历史记录变化 onpopstate
  63. window.onpopstate = function () {
  64. console.log(history.state)
  65. if(history.state){
  66. console.log("有历史")
  67. }else{
  68. console.log("无历史");
  69. lis[0].classList.add("active")
  70. }
  71. var thisId = history.state;
  72. for(var i=0;i<lis.length;i++){
  73. if(thisId == lis[i].dataset.id){
  74. lis[i].classList.add("active");
  75. }else{
  76. lis[i].classList.remove("active");
  77. }
  78. }
  79. }
  80. </script>
  81. </body>
  82. </html>