MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

当 一个窗口的哈希改变时就会触发 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;
	});
}());

Specifications

Specification Status Comment
WHATWG HTML Living Standard
GlobalEventHandlers
Living Standard  
HTML 5.1
GlobalEventHandlers
Recommendation  
HTML5
GlobalEventHandlers
Recommendation  

浏览器兼容性

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 5.0 (Yes) 3.6 (1.9.2)

8.0

oldURL/newURL attributes are not supported.

10.6 5.0
Feature Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.2 (Yes) 1.0 (1.9.2) 9.0 11.0 5.0

文档标签和贡献者

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