Window:hashchange 事件

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

当 URL 的片段标识符(以 # 符号开头和之后的 URL 部分)更改时,将触发 hashchange 事件。

语法

在如 addEventListener() 等方法中使用事件名称,或设置事件处理器属性。

js
addEventListener("hashchange", (event) => {});
onhashchange = (event) => {};

事件类型

事件属性

HashChangeEvent.newURL 只读

一个字符串,表示窗口导航到的新 URL。

HashChangeEvent.oldURL 只读

一个字符串,表示导航窗口的上一个 URL。

事件处理器别名

除了 Window 接口以外,事件处理器属性 onhashchange 同样可以用于以下目标:

示例

你可以在 addEventListener 方法中使用 hashchange 事件:

js
window.addEventListener(
  "hashchange",
  () => {
    console.log("哈希已更改!");
  },
  false,
);

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

js
function locationHashChanged() {
  if (location.hash === "#cool-feature") {
    console.log("你正在访问一个很酷的功能!");
  }
}

window.onhashchange = locationHashChanged;

规范

Specification
HTML
# event-hashchange
HTML
# handler-window-onhashchange

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
hashchange event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Has more compatibility info.

参见