pushState和onpopstate是用来作页面的无刷新,但是可以产生history(历史记录)和改变url的

简单介绍
1.pushState

history.pushState({state:1}, "title", "#");
//三个参数  第一个是历史记录(必须写)  第二个是title(可以不写,直接写""),第三个是接下来的url后面加的东西
//第一个参数可以当poptate触发后,通过history.state 获取到

2.onpopstate

 window.onpopstate=popStateHandle; //onpopstate 这是个事件,当页面返回和前进时触发
上面的介绍看着很抽象,写了个小demo,在demo中更好的理解。

js代码

        var arr,divs;
        init()
        function init(){
            // 当历史前进或者后退时就会收到这个事件
            window.onpopstate=popStateHandler;
            arr=Array.from(document.getElementsByTagName("p"));
            divs=Array.from(document.getElementsByTagName("div"));
            arr[0].style.display="block";
            for(var i=0;i<divs.length;i++){
                divs[i].onclick=clickHandler;  //遍历每个div标签,点击时触发事件
            }
            
        }


        function clickHandler(){
           var index=divs.indexOf(this);   //获取点击元素的下标
        //    history.pushState({state:1},"","#"+this.innerHTML);  
            // 在历史记录列表中增加数据,后面的#内容标示当前跳转部分
             history.pushState({index:index}, "", "#" +this.innerHTML);//设置url的改变和历史记录
             changeMenu(index);    //点击后触发改变内容的函数
        }

        function popStateHandler(){
            console.log(history.state);  //打印历史记录   就是pushstate的第一个参数
            changeMenu(history.state.index)   //页面返回时触发改变内容的函数
        }

       function changeMenu(index){
        for(var i=0;i<arr.length;i++){
                if(i===index){
                    arr[i].style.display="block";
                }else{
                    arr[i].style.display="none";
                }
            }
       }

html标签

<div>水果</div>
    <div>蔬菜</div>
    <div>零食</div>
    <div>饮料</div>
    <br>
    <br>
    <p>猕猴桃
        苹果
        梨</p>
    <p>白菜
        土豆
        地瓜</p>
    <p>辣条
        牛肉干
        薯片</p>
    <p>可乐
        雪碧
        果汁</p>

css渲染

        div{
            width: 100px;
            height: 40px;
            font-size: 30px;
            line-height: 40px;
            text-align: center;
            border:1px solid #000000;
            float: left;
            margin-left: 50px;
            user-select: none;
        }
        p{
            clear: both;
            display: none;
        }

上面的代码我只注释了js代码,html和css我没说明,不过相信看到这篇文章的都不需要说明。

posted on 2020-07-15 14:31  94Lucky  阅读(1257)  评论(0编辑  收藏  举报