练习5_历史管理history.html 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. ul {
  16. display: flex;
  17. }
  18. li {
  19. width: 200px;
  20. height: 100px;
  21. color: white;
  22. background-color: gray;
  23. line-height: 100px;
  24. text-align: center;
  25. font-size: 40px;
  26. font-weight: bold;
  27. }
  28. .active {
  29. background-color: black;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <!-- 第一步实现样式 -->
  35. <div>
  36. <ul>
  37. <!-- 添加自定义属性 data-index 来存储索引 -->
  38. <li data-index="0" class="active">first</li>
  39. <li data-index="1">second</li>
  40. <li data-index="2">third</li>
  41. </ul>
  42. </div>
  43. <script>
  44. // 第二步绑定事件
  45. var aLi = document.querySelectorAll("li");
  46. // 循环绑定事件
  47. for(var i=0;i<aLi.length;i++){
  48. aLi[i].onclick = function(){
  49. // 移除所有选中状态
  50. for(var j=0;j<aLi.length;j++){
  51. aLi[j].classList.remove("active");
  52. }
  53. // 为自己 (当前点击的按钮)添加状态
  54. this.classList.add("active");
  55. //添加历史记录
  56. // 获取自定义属性 data-index的值
  57. var dataIndex = this.dataset.index;
  58. // 把索引存储到历史记录中
  59. history.pushState(dataIndex,"");
  60. }
  61. }
  62. // 第三步监听历史变化
  63. window.onpopstate = function(){
  64. var historyState = history.state;
  65. // 将获取的state值转换为数字
  66. historyState = parseInt(historyState);
  67. // 移除所有选中状态
  68. for(var j=0;j<aLi.length;j++){
  69. aLi[j].classList.remove("active");
  70. }
  71. // 控制对应li添加选中状态
  72. aLi[historyState].classList.add("active");
  73. }
  74. </script>
  75. </body>
  76. </html>