1、hash模式:原理是onhashchange事件,url都会被浏览器记录下来,只能改变#后面的url片段
2、history模式:根据history api中的pushState,replaceState两个方法。
通过pushstate把页面的状态保存在state对象中,当页面的url再变回这个url时,可以通过event.state取到这个state对象,从而可以对页面状态进行还原,这里的页面状态就是页面字体颜色,其实滚动条的位置,阅读进度,组件的开关的这些页面状态都可以存储到state的里面
<script type="text/javascript">
window.onhashchange = function(event){
console.log(event.oldURL, event.newURL);
let hash = location.hash.slice(1);
document.body.style.color = hash;
}
window.history.pushState({color:'red'}, 'red', '');
window.onpopstate = function(event){
console.log(event.state);
if(event.state && event.state.color === 'red'){
document.body.style.color = 'red';
}
}
</script>