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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 data-val="first" class="tab-btn active">first</div>
  29. <div data-val="second" class="tab-btn">second</div>
  30. <div data-val="third" class="tab-btn">third</div>
  31. </div>
  32. <script>
  33. var tabBtns = document.querySelectorAll('.tab-btn');
  34. tabBtns.forEach((item)=>{
  35. item.onclick = function(){
  36. tabBtns.forEach((item)=>{
  37. item.classList.remove("active");
  38. });
  39. this.classList.add("active");
  40. let thisVal = this.dataset.val;
  41. window.history.pushState(thisVal,"");
  42. }
  43. })
  44. window.onpopstate = function(){
  45. let thisState = window.history.state;
  46. tabBtns.forEach((item)=>{
  47. if(item.dataset.val == thisState){
  48. tabBtns.forEach((item)=>{
  49. item.classList.remove("active");
  50. });
  51. item.classList.add("active");
  52. }
  53. });
  54. }
  55. </script>
  56. </body>
  57. </html>