window.history的簡單回顧html
window.history.back(); window.history.forward(); windiw.history.go(-1);//至關於back() window.history.go(1);//至關於forwar() window.history.go(0);//至關於刷新 window.history.length;//查看歷史記錄棧中一共有多少個記錄
對歷史記錄點進行修改ajax
history.pushState(state, title, url)瀏覽器
>接受三個參數: >state:狀態對象,記錄歷史記錄點的額外對象,可爲null >title:頁面標題,目前因此瀏覽器都不支持,須要的話能夠用document.title來設置 >url:新的網址,必須同域,瀏覽器地址欄會顯示這個網址 window.history.pushState(null, '', 'a.html'); //頁面不刷新,只是改變history對象,地址欄會改變 window.history.pushState(null, '', '#aaa'); >//url參數帶了hash值並不會觸發hashchange事件
history.replaceState(state, title, url)網站
window.history.replaceState({a:1}, '', 'b.html')
history.state屬性url
window.history.state //{a:1}
監聽歷史記錄spa
window.onhashchange = function(){ console.log(location.hash) };//hashchange事件必須綁定再widnow對象上
if(('onhashchange' in window) && ((typeof document.documentMode === 'undefined') || document.documentMode == 8)) { //在IE8以ie7的模式運行時,window下存在onhashchange這個方法,可是永遠不會觸發這個事件 //不能用 typeof window.onhashchange === ‘undefined’ 來檢測,由於不少支持onhashchange的瀏覽器下,其初始值就是undefined window.onhashchange = function() { console.log(window.location.hash); }; } else {//不支持onhashchange用定時器判斷hash是否改變 var location = window.location; var oldHash = location.hash; setInterval(function() { var newHash = location.hash; if(newHash === oldHash) { console.log(location.hash); } }) }
window.oppopstate = function(event) { console.log(event.state); }//event.state的值是history.state的值
簡單應用:無刷新頁面,改變url,產生歷史記錄code