One-AnDong / PandaTalk

书写文字,让技术沉淀
1 stars 0 forks source link

浏览器学习-hisroty #6

Open One-AnDong opened 5 years ago

One-AnDong commented 5 years ago

history给我们保存状态的能力,通过pushState()添加激活历史条目,通过replaceState()修改当前激活的历史条目history接收三个参数

history.pushState({page:1},'title1','?page=1')

通过onpopstate事件的event对象会拷贝一份改历史记录条目的state,下面我们来实现一个小案例。

  history.pushState({
      color: 'red',
    },
    '',
    '?color=red') //添加并激活一个历史条目,histroy.html?color=red
  history.back() //返回上一条历史条目 histroy.html
  setTimeout(() => {
    history.forward() //设置定时器后前进到下一条历史条目 ,histroy.html?color=red
  }, 1000)
  // 状态的历史记录条目发生变化时, popstate事件就会在对应window对象上触发.
  window.onpopstate = function (e) {
    console.log(e.state)
    if (e.state && e.state.color === 'red') {
      document.body.style.color = 'red'
    }
  }

通过pushstate把页面的状态保存在state对象中,当页面的url再变回这个url时,可以通过event.state取到这个state对象,从而可以对页面状态进行还原,这里的页面状态就是页面字体颜色,其实滚动条的位置,阅读进度,组件的开关的这些页面状态都可以存储到state的里面。

补充资料

  window.onpopstate = function (event) {
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
  };
  //绑定事件处理函数.
  history.pushState({
    page: 1
  }, "title 1", "?page=1"); //添加并激活一个历史记录条目 http://example.com/example.html?page=1,条目索引为1
  history.pushState({
    page: 2
  }, "title 2", "?page=2"); //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2
  history.replaceState({
    page: 3
  }, "title 3", "?page=3"); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为3
  history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}"
  history.back(); // 弹出 "location: http://example.com/example.html, state: null
  history.go(2); // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3}
One-AnDong commented 5 years ago

补充关于hash的一些知识点,我们histroy是html5 的 api,在此之前还有个hash,浏览器通过记录hash值让页面不刷新跳转,背后的原理其实onhashchange 事件,该事件是在window上的,下面通过一个小demo来理解

<body>
  <div>这是一段测试hash的小文字,改变hash值将触发hashchange事件,这段文字的颜色取自hash值</div>
</body>
window.onhashchange = function (e) {
    console.log('form:', e.newURL, 'from:', e.oldURL)
    document.body.style.color = location.hash.slice(1)
    console.log(location.hash)
  }

Snip20190820_2 Snip20190820_3 Snip20190820_4 Snip20190820_5

这样我们就实现了对页面状态的保持,在chrome中前进后退我们的页面,但我们只能通过修改#后面的值来达到我们需要的效果,这样自由性会非常低,所以有了我们的history模式

One-AnDong commented 5 years ago

具体代码在https://github.com/One-AnDong/FE.BASE/tree/master/Bom%E5%9F%BA%E7%A1%80