星空网 > 软件开发 > 网页设计

图解用HTML5的popstate如何玩转浏览器历史记录

一、popstate用来做什么的?
简而言之就是HTML5新增的用来控制浏览器历史记录的api。

二、过去如何操纵浏览器历史记录?
window.history对象,该对象上包含有length和state的两个值,在它的__proto__上继承有back、forward、go等几个功能函数
在popstate之前,我们可以利用back、forward、go对history进行后退和前进操作。
例如:
history.back(); (后退一步,使用history.go(-1)也可实现后退效果)
弊端:只能操作前进后退,但是无法控制前进后要去哪,history.length都只会维持原来的状态

三、popstate的怎么用?
HTML5的新API扩展了window.history,使历史记录点更加开放了。可以存储当前历史记录点pushState、替换当前历史记录点replaceState、监听历史记录点popstate。

pushState、replaceState两者用法差不多。

使用方法:

history.pushState(data,title,url);
//其中第一个参数data是给state的值;第二个参数title为页面的标题,但当前所有浏览器都忽略这个参数,传个空字符串就好;第三个参数url是你想要去的链接;

replaceState用法类似,例如:history.replaceState("首页","",location.href+ "#news");

 

两者区别:pushState会改变history.length,而replaceState不改变history.length

通过下图我们可以对比看出pushState和replaceState的差别(注意看history.length的变化):

图解用HTML5的popstate如何玩转浏览器历史记录图解用HTML5的popstate如何玩转浏览器历史记录
<!DOCTYPE html><html><head lang="en">  <meta charset="UTF-8">  <title>图解用HTML5的popstate如何玩转浏览器历史记录</title></head><body><span class="js-news">新闻</span><span class="js-music">音乐</span><script>  var locationHref = location.href;  document.addEventListener("click", function (event) {    var target = event.target;    if (target.className == "js-news") {      history.pushState("首页", "", locationHref + "#news");    } else if (target.className == "js-music") {      history.pushState("音乐", "", locationHref + "#music");    }  });  /*  document.addEventListener("click",function(event){   var target = event.target;   if(target.className == "js-news"){   history.replaceState("首页","",locationHref + "#news");   }else if(target.className == "js-music"){   history.replaceState("音乐","",locationHref + "#music");   }   });*/    window.addEventListener("popstate", function () {    console.log(history.state);  })</script></body></html>

View Code

 

图解用HTML5的popstate如何玩转浏览器历史记录图解用HTML5的popstate如何玩转浏览器历史记录

 

四、监听浏览器状态(popstate)变化事件
可以理解为监听浏览器后退、前进的操作,只要后退或者前进就会触发。在上面的demo中,我们预先做了如下操作:打开页面→点击“新闻”→点击“音乐”→再点击“新闻”,产生了4个history记录。然后监听浏览器后退和前进的状态变化,如下图所示:

图解用HTML5的popstate如何玩转浏览器历史记录




原标题:图解用HTML5的popstate如何玩转浏览器历史记录

关键词:HTML

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

澳门国际货运:https://www.goluckyvip.com/tag/101703.html
国际物流澳大利亚:https://www.goluckyvip.com/tag/101704.html
17track国际快递查询网:https://www.goluckyvip.com/tag/101705.html
达国际快递:https://www.goluckyvip.com/tag/101706.html
广州速达国际货运:https://www.goluckyvip.com/tag/101707.html
广州赛拉国际货运:https://www.goluckyvip.com/tag/101708.html
深圳到西安自驾路线攻略 深圳到西安自驾最佳路线:https://www.vstour.cn/a/411228.html
松花蛋是哪里的特产松花蛋的产地:https://www.vstour.cn/a/411229.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流