Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

HashChangeEvent

当URL中的片段标识符发生改变时触发(URL中紧跟'#'号的部分,包括‘#’号)

 

摘要

规格
HTML5
接口
HashChangeEvent
冒泡
Yes
可撤销
No
目标
defaultView
默认行为
None

属性

Property Type Description
target 只读 EventTarget The browsing context (<code>window</code>).
type 只读 DOMString The type of event.
bubbles 只读 boolean Does the event normally bubble?
cancelable 只读 boolean Is it possible to cancel the event?
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)
Support for the oldURL/newURL attributes added in Firefox 6.
8.0
oldURL/newURL attributes are not supported.
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.0


There are several fallback scripts listed on this page. Basically those scripts check the location.hash at a regular interval. Here is a version that allows only one handler to be bound to the <code>window.onhashchange</code> property:

(function(window) {

  // exit if the browser implements that event
  if ( "onhashchange" in window.document.body ) { return; }

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

  // check the location hash on a 100ms interval
  setInterval(function() {
    var newURL = location.href,
      newHash = location.hash;

    // if the hash has changed and a handler has been bound...
    if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
      // execute the handler
      window.onhashchange({
        type: "hashchange",
        oldURL: oldURL,
        newURL: newURL
      });

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

})(window);

语法

window.onhashchange = funcRef;

or

<body onhashchange="funcRef();">

or

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

参数

funcRef
函数引用

示例

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

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

window.onhashchange = locationHashChanged;

hashchange 事件

触发的hashchange事件有如下属性:

属性 类型 描述
newURL DOMString hash改变后窗口的url
oldURL DOMString hash改变前的url

文档标签和贡献者

 此页面的贡献者: wzjg520
 最后编辑者: wzjg520,