美文网首页
HTML5 history 页面历史记录

HTML5 history 页面历史记录

作者: Do_Du | 来源:发表于2020-04-01 17:23 被阅读0次

DOM window 对象通过history对象提供了对浏览器历史的访问。

跳转属性

back(): 向后跳转
forward(): 向前跳转
go(): 跳转至第n页

// 在history中向后跳转
window.history.back();
window.history.go(-1);

// 向前跳转
window.history.forward();
window.history.go(1);

// 当前页
window.history.go(0);

添加和修改历史记录中的条目

pushState(状态对象,标题(可为空),URL(可选的)):记录历史记录
window.onpopstate:触发 调用历史记录

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  *{
    margin: 0;
    padding: 0;
  }
  .body{
    background: gray;
  }
  #box{
    width: 800px;
    height: 400px;
    background-color: #ddd;
    margin: 100px auto;
    display: flex;
    justify-content: space-around;
    align-items: center;;
  }
  ul{
    width: 200px;
    height:300px;
    border: 1px solid #fff;
    border-bottom: none;
  }
  li{
    list-style: none;
    line-height: 100px;
    border-bottom: 1px solid #fff;
    text-align: center;
  }
  #con{
    width: 500px;
    height: 300px;
    border: 1px solid#fff;
  }
</style>
<body>
  <!-- 移动端app没有记录历史记录 模仿记录历史记录-->
  <div id="box">
    <ul id="list"></ul>
    <div id="con"></div>
  </div>

  <script>
    var list = document.getElementById('list');
    var con = document.getElementById('con');
    
    var json = {
      '小米': '小米商城',
      '华为':'华为商城',
      '苹果': '苹果商城'
    };
    var str = '';
    var arr = [];
    for (var key in json) {
      str +='<li data-name="'+key+'">' + key + '</li>';
      arr.push(json[key])
    }
    list.innerHTML = str;
    console.log('arr',arr);
    //以上完成渲染数据

    var lis = list.querySelectorAll('li');
    for (var i = 0; i < arr.length; i++) {
      
     lis[i].index = i;
     console.log('lis',lis[i]);

     lis[i].onclick = function () { // 实现点击切换
     
       con.innerHTML = arr[this.index];
       window.history.pushState(arr[this.index],'',this.dataset['name']);
     }
    }

    window.onpopstate = function (e) {
      console.log('11')
      var e = e || e.target;
      console.log(e)
      con.innerHTML = e.state;
    }
  </script>
</body>
</html>

案例:tab切换,记录内容


image.png
image.png
image.png

相关文章

网友评论

      本文标题:HTML5 history 页面历史记录

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