当URL的片段标识符更改时,将触发hashchange事件 (跟在#符号后面的URL部分,包括#符号)
通用信息
- 规范
- HTML5
- 接口
- HashChangeEvent
- 是否冒泡
- 是
- 能否取消默认行为
- 不能
- 目标
- defaultView
- 默认行为
- 无
属性
| Property | Type | Description |
|---|---|---|
target 只读 |
EventTarget |
浏览上下文 (<code>window</code>). |
type 只读 |
DOMString |
The type of event. |
bubbles 只读 |
Boolean |
Whether the event normally bubbles or not |
cancelable 只读 |
Boolean |
Whether the event is cancellable or not? |
oldURL 只读 |
string | The previous URL from which the window was navigated. |
| newURL 只读 | string |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 5.0 | 3.6 (1.9.2) Firefox 6 中加入对 oldURL/newURL 属性的支持. |
8.0 | 10.6 | 5.0 |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | 2.2 | 1.0 (1.9.2) | 9.0 | 11.0 | 5. |
这个页面里有几个用JavaScript模拟该事件的脚本,原理基本上都是隔一段时间检测一下location.hash是否发生变化.下面的这个实现可以在<code>window.onhashchange</code>属性上绑定事件处理函数:
(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);