一、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如何玩转浏览器历史记录新闻
音乐
varlocationHref=location.href;
document.addEventListener("click",function(event) {vartarget=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);
})