图解用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的变化):

<!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

 

 

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

posted @ 2016-01-08 23:41  水乙  阅读(20229)  评论(3编辑  收藏  举报