8_历史管理history.html 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  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. <!-- 历史管理 history -->
  10. <button id="btn">点击我</button>
  11. <script>
  12. // 获取元素
  13. var btn = document.getElementById("btn");
  14. // 绑定事件
  15. btn.onclick = function () {
  16. // 点击按钮后,改变历史记录
  17. // history中通过pushState方法添加历史记录
  18. // pushState 有三个值 第一个参数是添加的值 第二个参数是标题(不能省略一帮为空字符串) 第三个参数是url
  19. // history.pushState(val,title,url);
  20. var ran = Math.random();
  21. history.pushState(ran,"");
  22. }
  23. // 监听历史记录变化 onpopstate
  24. window.onpopstate = function () {
  25. console.log(history.state);
  26. }
  27. // history 与 hash 区别
  28. // history不会改变url,hash会改变url
  29. </script>
  30. </body>
  31. </html>