在js中处理URL锚点更改事件

Bog*_*iev 87 javascript event-handling fragment-identifier dom-events hashchange

如何编写将在URL锚点的任何更改上执行的JavaScript回调代码?

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

And*_*y E 124

Google自定义搜索引擎使用计时器根据以前的值检查哈希,而单独域上的子iframe更新父级的位置哈希以包含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
Run Code Online (Sandbox Code Playgroud)

谷歌Chrome 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);
    }
Run Code Online (Sandbox Code Playgroud)

把它放在一起:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • @Timo:你......没看过我的回答,是吗?:-P (2认同)

Fab*_*rts 7

我建议使用addEventListener而不是覆盖window.onhashchange,否则您将阻止其他插件的事件。

window.addEventListener('hashchange', function() {
...
})
Run Code Online (Sandbox Code Playgroud)

看看当今全球浏览器的使用情况,不再需要回退。