hashchange

hashchange事件会在页面URL中的片段标识符(第一个#号开始到末尾的所有字符,包括#号)发生改变时触发.

通用信息

规范
HTML5
接口
HashChangeEvent
是否冒泡
能否取消默认行为
不能
目标
defaultView
默认行为

属性

 

PropertyTypeDescription
targetRead onlyEventTargetThe browsing context (<code>window</code>).
typeRead onlyDOMStringThe type of event.
canBubbleRead onlybooleanDoes the event normally bubble?
cancelableRead onlybooleanIs it possible to cancel the event?
oldURLstringThe previous URL from which the window was navigated. Read only
newURLstringThe new URL to which the window is navigating. Read only

 

浏览器兼容性

 

  • Desktop  
  • Mobile
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5.03.6 (1.9.2)
Support for the oldURL/newURL attributes added in Firefox 6.
8.010.65.0

 

这个页面里有几个用JavaScript模拟该事件的脚本,原理基本上都是隔一段时间检测一下location.hash是否发生变化.下面的这个实现可以在<code>window.onhashchange</code>属性上绑定事件处理函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
( function (window) {
 
   // 如果浏览器原生支持该事件,则退出 
if ( "onhashchange" in window.document.body ) { return ; }
 
   var location = window.location,
     oldURL = location.href,
     oldHash = location.hash;
 
   // 每隔100ms检测一下location.hash是否发生变化
   setInterval( function () {
     var newURL = location.href,
       newHash = location.hash;
 
     // 如果hash发生了变化,且绑定了处理函数...
     if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
       // execute the handler
       window.onhashchange({
         type: "hashchange" ,
         oldURL: oldURL,
         newURL: newURL
       });
 
       oldURL = newURL;
       oldHash = newHash;
     }
   }, 100);
 
})(window);

相关事件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值