HashChangeEvent

HashChangeEvent 接口表示一个变化事件,当 URL 中的片段标识符发生改变时,会触发此事件。

片段标识符指 URL 中 # 号和它以后的部分。

属性

 这个接口也从 Event 中继承属性。

HashChangeEvent.newURL 只读
window即将导航到达的新 URL。
HashChangeEvent.oldURL 只读
window此前导航到达过的URL。

方法

这个接口没有自己的方法,但从 Event 中继承方法

示例

井号内容变化的语法选择

你可以选择使用下述的任一方法监听 hashchange 事件。

window.onhashchange = funcRef;

<body onhashchange="funcRef();">

window.addEventListener("hashchange", funcRef, false);

基本示例

function locationHashChanged() {
  if (location.hash === '#somecoolfeature') {
    somecoolfeature();
  }
}

window.addEventListener('hashchange', locationHashChanged);

回落方法(Polyfill)

在 Modernizr GitHub page 中列出了几种回落(fallback)脚本。基本上,这些脚本每隔一段时间检查以此 location.hash。这里是其中一个版本,其仅允许一个处理程序(handler)绑定在 onhashchange 属性上:

(function(window) {

  // 如果浏览器已经实现了此事件,则退出函数
  if ( "onhashchange" in window.document.body ) return;

  var location = window.location,
      oldURL  = location.href,
      oldHash = location.hash;

  // 每隔 100 毫秒,检查一次片段标识符
  setInterval(function() {
    var newURL  = location.href,
        newHash = location.hash;

    // 如果片段标识符有变化,且处理程序存在
    if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
      // 执行处理程序
      window.onhashchange({
        type: "hashchange",
        oldURL: oldURL,
        newURL: newURL
      });

      oldURL = newURL;
      oldHash = newHash;
    }
  }, 100);

})(window);

规范

规范 状态 备注
HTML Living Standard
HashChangeEvent
Living Standard Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
HashChangeEventChrome Full support 5Edge Full support 12Firefox Full support 3.6IE Full support 8Opera Full support 10.6Safari Full support 5WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support 11Safari iOS Full support 5Samsung Internet Android Full support Yes
newURLChrome Full support YesEdge Full support 12Firefox Full support 6IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
oldURLChrome Full support YesEdge Full support 12Firefox Full support 6IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support

相关事件