javascript - 在 Javascript 中处理 URL 片段标识符( anchor )更改事件

标签 javascript event-handling dom-events fragment-identifier hashchange

如何编写将在 URL 片段标识符( anchor )发生任何更改时执行的 Javascript 回调代码?

例如从http://example.com#ahttp://example.com#b

最佳答案

Google 自定义搜索引擎使用计时器根据先前的值检查散列,而单独域上的子 iframe 更新父的位置散列以包含 iframe 文档正文的大小。当计时器捕捉到变化时,父级可以调整 iframe 的大小以匹配主体的大小,这样就不会显示滚动条。

类似下面的东西实现了同样的效果:

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
        storedHash = window.location.hash;
        hashChanged(storedHash);
    }
}, 100); // Google uses 100ms intervals I think, might be lower

谷歌浏览器 5、Safari 5、Opera 10.60 , Firefox 3.6Internet Explorer 8 所有都支持hashchange事件:

if ("onhashchange" in window) // does the browser support the hashchange event?
    window.onhashchange = function () {
        hashChanged(window.location.hash);
    }

并将其放在一起:

if ("onhashchange" in window) { // event supported?
    window.onhashchange = function () {
        hashChanged(window.location.hash);
    }
}
else { // event not supported:
    var storedHash = window.location.hash;
    window.setInterval(function () {
        if (window.location.hash != storedHash) {
            storedHash = window.location.hash;
            hashChanged(storedHash);
        }
    }, 100);
}

jQuery 还有一个插件可以检查 hashchange 事件并在必要时提供自己的事件 - http://benalman.com/projects/jquery-hashchange-plugin/ .

编辑:(再次)更新了浏览器支持。

关于javascript - 在 Javascript 中处理 URL 片段标识符( anchor )更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161906/

相关文章:

javascript - React 中 this.setState 的异步特性

javascript - 如果我绑定(bind)一个已经绑定(bind)的 JQuery 事件会发生什么?

JavaScript Array.map(parseInt) 导致 NaN 错误

Delphi 空闲处理程序仅在我移动鼠标时触发

jquery - 将类中所有元素的函数绑定(bind)到事件的 Angular 方式

javascript - Express 生成器 - TypeError : app. set 不是一个函数

javascript - 事件处理程序中的参数 - Javascript

jquery - 忽略 Mouseover 元素的子元素中的 Mouseout 事件

javascript - ASP.NET 中的 OnClientClick 事件

javascript - 从 Javascript 库调用的事件