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();
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>