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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. margin:100px auto;
  19. }
  20. .box ul{
  21. display: flex;
  22. }
  23. .box li{
  24. width: 200px;
  25. height: 100px;
  26. background-color: #aaa;
  27. font-size: 50px;
  28. line-height: 100px;
  29. text-align: center;
  30. color: #fff;
  31. }
  32. .box .active{
  33. background-color: #111;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <div class="box">
  39. <ul>
  40. <li class="active" data-id="first">first</li>
  41. <li data-id="second">second</li>
  42. <li data-id="third">third</li>
  43. </ul>
  44. </div>
  45. <script>
  46. var aLi = document.querySelectorAll("li");
  47. //定义函数处理选中状态
  48. function handleActive(key){
  49. for(var i=0;i<aLi.length;i++){
  50. if(aLi[i].dataset.id == key){
  51. aLi[i].classList.add("active");
  52. }else{
  53. aLi[i].classList.remove("active");
  54. }
  55. }
  56. }
  57. // 绑定标签按钮点击事件
  58. for(var i=0;i<aLi.length;i++){
  59. aLi[i].onclick = function(){
  60. var _id = this.dataset.id;
  61. // 调用处理选中状态函数
  62. handleActive(_id);
  63. // 添加历史记录
  64. history.pushState(_id,"");
  65. }
  66. }
  67. // 监听history变化
  68. window.onpopstate = function(event){
  69. var _state = event.state;
  70. console.log(_state);
  71. // 调用处理选中状态函数
  72. // handleActive(_state);
  73. if(_state){
  74. handleActive(_state);
  75. }else{
  76. handleActive(aLi[0].dataset.id);
  77. }
  78. }
  79. </script>
  80. </body>
  81. </html>