history.js 一个无刷新就可改变浏览器栏地址的插件(不依赖jquery)

简介

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

竖子敢尔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值