1、popstate用来作什么的?
简而言之就是HTML5新增的用来控制浏览器历史记录的api。html
2、过去如何操纵浏览器历史记录?
window.history对象,该对象上包含有length和state的两个值,在它的__proto__上继承有back、forward、go等几个功能函数
在popstate以前,咱们能够利用back、forward、go对history进行后退和前进操做。
例如:
history.back(); (后退一步,使用history.go(-1)也可实现后退效果)
弊端:只能操做前进后退,可是没法控制前进后要去哪,history.length都只会维持原来的状态api
3、popstate的怎么用?
HTML5的新API扩展了window.history,使历史记录点更加开放了。能够存储当前历史记录点pushState、替换当前历史记录点replaceState、监听历史记录点popstate。浏览器
pushState、replaceState二者用法差很少。ide
使用方法:函数
history.pushState(data,title,url);
//其中第一个参数data是给state的值;第二个参数title为页面的标题,但当前全部浏览器都忽略这个参数,传个空字符串就好;第三个参数url是你想要去的连接;
replaceState用法相似,例如:history.replaceState("首页","",location.href+ "#news");url
二者区别:pushState会改变history.length,而replaceState不改变history.lengthspa
经过下图咱们能够对比看出pushState和replaceState的差异(注意看history.length的变化):code
<!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>
4、监听浏览器状态(popstate)变化事件
能够理解为监听浏览器后退、前进的操做,只要后退或者前进就会触发。在上面的demo中,咱们预先作了以下操做:打开页面→点击“新闻”→点击“音乐”→再点击“新闻”,产生了4个history记录。而后监听浏览器后退和前进的状态变化,以下图所示:htm