--- title: 'Window: hashchange event' slug: Web/API/Window/hashchange_event tags: - API - DOM - Event - HashChange - Window - onhashchange - 事件 - 参考 translation_of: Web/API/Window/hashchange_event ---

{{APIRef}}

当URL的片段标识符更改时,将触发hashchange事件 (跟在#符号后面的URL部分,包括#符号)

Bubbles Yes
Cancelable No
Interface {{domxref("HashChangeEvent")}}
Event handler {{domxref("WindowEventHandlers/onhashchange", "onhashchange")}}

示例

你可以在 {{domxref("EventTarget/addEventListener", "addEventListener")}} 方法中使用 hashchange 事件:

window.addEventListener('hashchange', function() {
  console.log('The hash has changed!')
}, false);

或使用 onhashchange 事件处理程序属性:

function locationHashChanged() {
  if (location.hash === '#cool-feature') {
    console.log("You're visiting a cool feature!");
  }
}

window.onhashchange = locationHashChanged;

规范

规范 状态 注释
{{SpecName('HTML WHATWG', 'indices.html#event-hashchange', 'hashchange')}} {{Spec2('HTML WHATWG')}} Initial definition

浏览器兼容性

{{Compat("api.Window.hashchange_event")}}

参见