簡介
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