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 () {
- // 向历史记录中添加一条记录 history.pushState
- // 一共有两个参数 第一个参数是状态值 第二个参数是标题(一般不用传输但必有这个参数所以传空值)
- history.pushState(1,"");
- oH1.innerText = "内容一";
- }
- oBtn2.onclick = function () {
- history.pushState(2,"");
- oH1.innerText = "内容二";
- }
- oBtn3.onclick = function () {
- history.pushState(3,"");
- oH1.innerText = "内容三";
- }
- // 监听history值的变化
- window.onpopstate = function(){
- console.log(history.state);
- if(history.state == 1){
- oH1.innerText = "内容一";
- }else if(history.state == 2){
- oH1.innerText = "内容二";
- }else if(history.state == 3){
- oH1.innerText = "内容三";
- }
- }
- </script>
- </body>
- </html>
|