9_历史管理hash.html 1.6 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. // 设置 hash 值以改变 浏览器地址栏 历史
  20. // location.hash = '#hello';
  21. location.hash = "#1"
  22. oH1.innerText = "内容一";
  23. }
  24. oBtn2.onclick = function(){
  25. location.hash = "#2";
  26. oH1.innerText = "内容二";
  27. }
  28. oBtn3.onclick = function(){
  29. location.hash = "#3";
  30. oH1.innerText = "内容三";
  31. }
  32. // 监听 hash 值的改变
  33. window.onhashchange = function(){
  34. // console.log("132")
  35. // 当点击向前 或者 向后按钮 时 会触发 hashchange 事件
  36. // 获取当前 hash 值
  37. var thisHash = location.hash;
  38. if(thisHash == "#1"){
  39. oH1.innerText = "内容一";
  40. }else if(thisHash == "#2"){
  41. oH1.innerText = "内容二";
  42. }else if(thisHash == "#3"){
  43. oH1.innerText = "内容三";
  44. }
  45. }
  46. </script>
  47. </body>
  48. </html>