History回顧
window.history表示window對象的歷史記錄
-
window.history的簡單回顧
- 歷史記錄中前進/后退,移動到指定歷史記錄點
window.history.back(); window.history.forward(); windiw.history.go(-1);//相當於back() window.history.go(1);//相當於forwar() window.history.go(0);//相當於刷新 window.history.length;//查看歷史記錄棧中一共有多少個記錄
-
對歷史記錄點進行修改
Html5的新API擴展了window.history,能夠做到可以存儲/替換/監聽歷史記錄點
-
history.pushState(state, title, url)
在history內新增一個歷史記錄,會增加后退效果,無刷新改變瀏覽器地址
>接受三個參數: >state:狀態對象,記錄歷史記錄點的額外對象,可為null >title:頁面標題,目前所以瀏覽器都不支持,需要的話可以用document.title來設置 >url:新的網址,必須同域,瀏覽器地址欄會顯示這個網址 window.history.pushState(null, '', 'a.html'); //頁面不刷新,只是改變history對象,地址欄會改變 window.history.pushState(null, '', '#aaa'); >//url參數帶了hash值並不會觸發hashchange事件
url參數如果是以'?'開頭,則url的值會代替seach的值,如果是以'#'開頭,則url的值會代替hash的值,如果是以'/'開頭,則url的值會代替/后的值。
-
history.replaceState(state, title, url)
使用姿勢跟pushState一樣,區別它是修改瀏覽歷史中的當前記錄,而並非創建一個新的,並不會增加后退效果,但是和pushState一樣都會改變當前地址欄的地址
window.history.replaceState({a:1}, '', 'b.html')
-
history.state屬性
返回當前頁面的state對象,想改變此對象可以給pushState和replaceState的第一個參數傳參
window.history.state //{a:1}
-
監聽歷史記錄
- hashchange:當前url的hash改變的時候會觸發該事件,ie6.7不支持。
window.onhashchange = function(){ console.log(location.hash) };//hashchange事件必須綁定再widnow對象上
做兼容,在ie6、7下可以用setInterval模擬
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); } }) }
- popstate: 當瀏覽記錄出現變化時,會觸發此事件,可以用此來監聽url
window.oppopstate = function(event) { console.log(event.state); }//event.state的值是history.state的值
調用pushState和replaceState事件不會觸發popstate事件,當點擊后退或者前進按鈕時才觸發,或者調用go()方法觸發;
ps:頁面第一次加載時,在load事件之后,Chrome和Safari能夠觸發popstate事件,而Firefox和Ie不能;
-
-
簡單應用:無刷新頁面,改變url,產生歷史記錄
很多網站都是左側為導航欄,右側為內容區,點擊導航欄,只刷新內容不刷新url,並且會生產瀏覽記錄可以點擊后退前進;
具體操作:點擊左側導航鏈接,阻止頁面跳轉,把地址pushState到瀏覽記錄,ajax局部刷新;點擊后退/前進時,用popstate監聽,ajax局部刷新,解決問題
參考文章:
http://www.impng.com/web-dev/hashchange-event-and-onhashchange.html