当 一个窗口的 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  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support 5Edge Full support YesFirefox Full support 3.6IE Full support 8Opera Full support 10Safari Full support 5WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 11Safari iOS Full support 5Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

文档标签和贡献者

此页面的贡献者: Arnie97, xgqfrms-GitHub, Ende93, vuji, teoli, khalid32, ziyunfei
最后编辑者: Arnie97,