history.js 一個無刷新就可改變瀏覽器欄地址的插件(不依賴jquery)
原文 http://ourjs.com/detail/5507ed1b1e8c708516000007
示例: http://browserstate.github.io/history.js/demo/
簡介
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); <h3>
效果
</h3>
<p>
當在HTML5瀏覽器中時地址欄的變化
</p>
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
</div> </div>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!