当 一个窗口的 hash (URL 中 # 后面的部分)改变时就会触发 hashchange 事件(参见 location.hash
)。
语法
window.onhashchange = funcRef;
或者
<body onhashchange="funcRef();">
以上操作将覆盖现有的事件处理程序。
为了添加一个新的事件处理程序,而不覆盖掉已有的其他事件处理程序,可以使用函数 "addEventListener"。
window.addEventListener("hashchange", funcRef, false);
参数
funcRef
- 对一个函数的引用。
例子
if ("onhashchange" in window) {
alert("该浏览器支持 hashchange 事件!");
}
function locationHashChanged() {
if (location.hash === "#somecoolfeature") {
somecoolfeature();
}
}
window.onhashchange = locationHashChanged;
hashchange 事件
hashchange
事件对象有下面两个属性:
属性 | 类型 | 描述 |
newURL |
DOMString |
当前页面新的URL |
oldURL |
DOMString |
当前页面旧的URL |
Workaround for event.newURL and event.oldURL
//let this snippet run before your hashchange event binding code
if(!window.HashChangeEvent)(function(){
var lastURL=document.URL;
window.addEventListener("hashchange",function(event){
Object.defineProperty(event,"oldURL",{enumerable:true,configurable:true,value:lastURL});
Object.defineProperty(event,"newURL",{enumerable:true,configurable:true,value:document.URL});
lastURL=document.URL;
});
}());
规范
Specification | Status | Comment |
---|---|---|
HTML Living Standard GlobalEventHandlers |
Living Standard | |
HTML 5.1 GlobalEventHandlers |
Recommendation | |
HTML5 GlobalEventHandlers |
Recommendation |
浏览器兼容性
BCD tables only load in the browser