<script type="text/javascript">a=location.hash;
if(a.indexOf('tyjlyy')<0){
window.history.replaceState({page:1},'','');
history.pushState({ nei:1},'ty',location.href+'#ty')
}window.addEventListener("popstate", function(e) { 
a=location.hash;
if(a.indexOf('ty')<0){
alert("请勿离开");
}
}, false);
</script>
我先说下我能理解的:判断链接后面有没有#tyjlyy 没有的话就给链接后面加入#ty
当按返回的时候,就删掉一个#ty  当#ty没有的情况下 就弹出请勿离开,这只是我看出大概的理解意思:其中:window.history.replaceState({page:1},'','');  这句我不明白具体是什么意思
history.pushState({ nei:1} 这部分又是什么意思还有window.addEventListener("popstate", function(e)  这里的"popstate", function(e) 是什么意思

解决方案 »

  1.   

    h5的history API,无刷新跳转(还能前进后退,会修改URL),具体去搜一下吧。了解过,没实际用过。
      

  2.   

    replaceState跟pushState都接受3个参数,一个为state,object,第二个是页面标题,第三个是页面URLreplaceState是修改历史记录
    pushState是想历史记录里增加你就把history想象成一个数组,replace是修改当前这个元素的内容,pushState是加新记录他们的第一个参数state,可以在popstate事件中,通过e.state获取到。每次有页面变化,会触发popstate事件
      

  3.   

    加了一个btn   应该能更好理解吧window.onload = function () {
                document.getElementById('btn').onclick = function () {
                    let a = location.hash;
                    if (a.indexOf('tyjlyy') < 0) {
                        window.history.replaceState({ page: 3 }, '', '');                 // 假想 page1            修改page1的state的值     
                        console.log(history.state);//page:3  口
                        window.history.pushState({ nei: 1 }, '', location.href + '#ty')   //假想 page2        直接跳转page2
                        console.log(history.state);//nei:1   口口
                    }
                }
            }
            window.addEventListener("popstate", function (e) {     //触发浏览器的前进  返回
                let a = location.hash;
                
                if (a.indexOf('ty') < 0) {
                    //当前为 page2
                    //返回  则取上一条历史记录(page1)所携带的参数  即page:3      
                    console.log(e.state);     
                   // alert("请勿离开");       虽然提示  但点确定后最后还是会离开
                } else {
                    //当前为 page1
                    //前进  则取上一条历史记录(page2)的所携带的参数
                    console.log(e.state);
                }
            }, false);
    楼上概念说的基本差不多了     
    这是我个人理解
    好乱.........
      

  4.   

    其实我最理解不了的还是:
    {page:1},'',''
    {nei:1},
      

  5.   

    这是参数啊,随便你传。再popstate时间里,可以通过e.state获取到传进去的对象
      

  6.   


    根据定义,replaceState({page:1},'','') -> replaceState( state object goes here,,'title goes here','optional url goes here');
    因此,三个参数如下:
    1. state object:{page: 1}. 这是JavaScript Object Literal. A JavaScript object literal is a comma-separated list of name-value pairs wrapped in curly braces. 如果你不懂Object Literal. 那恐怕很难解释了。
    2. title:‘’, title 是空的
    3. url: '', url 也是空的pushState 和 replaceState 的定义几乎是一样的。遇到类型问题,先查找定义。
    希望以上解释对你能有帮助。