10_历史管理history.html 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. </head>
  8. <body>
  9. <h1>内容一</h1>
  10. <button id="btn1">按钮一</button>
  11. <button id="btn2">按钮二</button>
  12. <button id="btn3">按钮三</button>
  13. <script>
  14. var oBtn1 = document.querySelector("#btn1");
  15. var oBtn2 = document.querySelector("#btn2");
  16. var oBtn3 = document.querySelector("#btn3");
  17. var oH1 = document.querySelector("h1");
  18. oBtn1.onclick = function () {
  19. // 向历史记录中添加一条记录 history.pushState
  20. // 一共有两个参数 第一个参数是状态值 第二个参数是标题(一般不用传输但必有这个参数所以传空值)
  21. history.pushState(1,"");
  22. oH1.innerText = "内容一";
  23. }
  24. oBtn2.onclick = function () {
  25. history.pushState(2,"");
  26. oH1.innerText = "内容二";
  27. }
  28. oBtn3.onclick = function () {
  29. history.pushState(3,"");
  30. oH1.innerText = "内容三";
  31. }
  32. // 监听history值的变化
  33. window.onpopstate = function(){
  34. console.log(history.state);
  35. if(history.state == 1){
  36. oH1.innerText = "内容一";
  37. }else if(history.state == 2){
  38. oH1.innerText = "内容二";
  39. }else if(history.state == 3){
  40. oH1.innerText = "内容三";
  41. }
  42. }
  43. </script>
  44. </body>
  45. </html>