history.js 一個無重新整理就可改變瀏覽器欄地址的外掛(不依賴jquery)

不淨之心發表於2015-11-10
[url]http://ourjs.com/detail/5507ed1b1e8c708516000007[/url]
示例: [url]http://browserstate.github.io/history.js/demo/[/url]


簡介

HTML4有一些對瀏覽歷史的前進後退API的支援如:
window.history.back();
window.history.forward();
window.history.go(-1);
window.history.go(1);


HTML5瀏覽器新新增了不重新整理改變網址地址的API:
var currentState = history.state;
var stateObj = { foo: "bar" };
window.history.pushState(stateObj, "page 2", "bar.html");


這些API構建單頁面無重新整理網站是十分有幫助的,很可惜他們在老瀏覽器中無法使用。history.js可以解決這個問題。


History.js優雅地支援所有瀏覽器的History/State的 API(pushState,replaceState,onPopState)。包括資料,title,replaceState。支援 jQuery,MooTools和Prototype。在HTML5瀏覽器,它使用原生API,可以直接修改URL,而無需再使用雜湊值。對於HTML4 瀏覽器則使用Hash值進行相容。

程式碼示例
(function(window,undefined){

// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
});

// Change our States
History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1"
History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2"
History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3"
History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4"
History.back(); // logs {state:3}, "State 3", "?state=3"
History.back(); // logs {state:1}, "State 1", "?state=1"
History.back(); // logs {}, "Home Page", "?"
History.go(2); // logs {state:3}, "State 3", "?state=3"

})(window);



效果
當在HTML5瀏覽器中時位址列的變化
www.mysite.com
www.mysite.com/?state=1
www.mysite.com/?state=2
www.mysite.com/?state=3
www.mysite.com/?state=4
www.mysite.com/?state=3
www.mysite.com/?state=1
www.mysite.com
www.mysite.com/?state=3

當在HTML4瀏覽器中時位址列的變化
www.mysite.com
www.mysite.com/#?state=1&_suid=1
www.mysite.com/#?state=2&_suid=2
www.mysite.com/#?state=3&_suid=3
www.mysite.com/#?state=4
www.mysite.com/#?state=3&_suid=3
www.mysite.com/#?state=1&_suid=1
www.mysite.com
www.mysite.com/#?state=3&_suid=3

相關文章