12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <h1>内容一</h1>
- <button id="btn1">按钮一</button>
- <button id="btn2">按钮二</button>
- <button id="btn3">按钮三</button>
- <script>
- var oBtn1 = document.querySelector("#btn1");
- var oBtn2 = document.querySelector("#btn2");
- var oBtn3 = document.querySelector("#btn3");
- var oH1 = document.querySelector("h1");
- oBtn1.onclick = function(){
- // 设置 hash 值以改变 浏览器地址栏 历史
- // location.hash = '#hello';
- location.hash = "#1"
- oH1.innerText = "内容一";
- }
- oBtn2.onclick = function(){
- location.hash = "#2";
- oH1.innerText = "内容二";
- }
- oBtn3.onclick = function(){
- location.hash = "#3";
- oH1.innerText = "内容三";
- }
- // 监听 hash 值的改变
- window.onhashchange = function(){
- // console.log("132")
- // 当点击向前 或者 向后按钮 时 会触发 hashchange 事件
- // 获取当前 hash 值
- var thisHash = location.hash;
- if(thisHash == "#1"){
- oH1.innerText = "内容一";
- }else if(thisHash == "#2"){
- oH1.innerText = "内容二";
- }else if(thisHash == "#3"){
- oH1.innerText = "内容三";
- }
- }
- </script>
- </body>
- </html>
|