Open One-AnDong opened 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)
}
这样我们就实现了对页面状态的保持,在chrome中前进后退我们的页面,但我们只能通过修改#后面的值来达到我们需要的效果,这样自由性会非常低,所以有了我们的history模式
具体代码在https://github.com/One-AnDong/FE.BASE/tree/master/Bom%E5%9F%BA%E7%A1%80
history给我们保存状态的能力,通过pushState()添加激活历史条目,通过replaceState()修改当前激活的历史条目history接收三个参数
stateObj(状态对象) : 是一个JavaScript对象类型,我们可以通过这个这个对象保存数据,可以在新的历史条目里(新的页面)获取到这个对象
title(标题) :目前浏览器大多不支持,保险起见可以传一个空字符串
url(地址): 新的页面地址,可选,传入的地址必须是同源,否则pushState()会抛出异常l 不传或传空字符串新历史条目默认为当前文档url
通过onpopstate事件的event对象会拷贝一份改历史记录条目的state,下面我们来实现一个小案例。
补充资料