美文网首页
关于history.pushState()和popstate和r

关于history.pushState()和popstate和r

作者: 冰红茶ht | 来源:发表于2018-01-05 14:44 被阅读0次

    上一篇用location.hash实现ajax前进后退功能,本文采用history.pushState()和popstate和 history.replaceState(). H5新特性实现。

    首先说下采用hash的问题
    • hash产生的历史记录是无法修改的,每次hash变化都会产生新的历史记录。
    • hash变化,url也会变化,用户体验不好,为啥呢?
    • hash只是一个字符串,不能存储更多的信息,这倒是真的。
    pushState参数说明

    history.pushState(state, title, url)
    1. state:与要跳转到的URL对应的状态信息
    2. title: 不知道干啥的,传空字符串就行
    3. url: 要跳转到的URL地址,不能跨域

    state改变的函数,相当于给hash赋值的函数
    function (id)  {
        history.pushState({ "id": id, }, "", "");
    }
    
    监听state的函数,相当于函数onhashchange
    window.onpopstate= function(id) {
        if(history.state) {
            var state = history.state; // 获取state
        }
    }
    
    替换state的函数,history.replace( );
    window.onpopstate = function() {
        if(history.state){
            var state = history.state;
            var count = 1+ state.visitTime;
            history.replaceState( { id: state.id, visitTime: count }, "", "" ); 
            //相当于修改当前路由状态和 localStorage 的setItem()差不多,
        }
    }
    

    参考原文 http://blog.csdn.net/aitangyong/article/details/46457855

    相关文章

      网友评论

          本文标题:关于history.pushState()和popstate和r

          本文链接:https://www.haomeiwen.com/subject/ilxsnxtx.html