HashChangeEvent
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
HashChangeEvent 接口表示一个变化事件,当 URL 中的片段标识符发生改变时,会触发此事件。
片段标识符指 URL 中 # 号和它以后的部分。
属性
这个接口也从 Event 中继承属性。
HashChangeEvent.newURL只读-
window 即将导航到达的新 URL。
HashChangeEvent.oldURL只读-
window 此前导航到达过的 URL。
方法
这个接口没有自己的方法,但从 Event 中继承方法。
示例
>基本示例
js
function locationHashChanged() { if (location.hash === "#somecoolfeature") { somecoolfeature(); } } window.addEventListener("hashchange", locationHashChanged); 回落方法(Polyfill)
在 Modernizr GitHub page 中列出了几种回落(fallback)脚本。基本上,这些脚本每隔一段时间检查以此 location.hash。这里是其中一个版本,其仅允许一个处理程序(handler)绑定在 onhashchange 属性上:
js
(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); 规范
| Specification |
|---|
| HTML> # the-hashchangeevent-interface> |