处理Javascript中的URL片段标识符(锚)更改事件 [英] Handle URL fragment identifier (anchor) change event in Javascript

查看:36
本文介绍了处理Javascript中的URL片段标识符(锚)更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写将对URL片段标识符(锚点)中的任何更改执行的Javascript回调代码?

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

推荐答案

Google Custom Search Engines使用计时器对照先前的值检查散列,而单独域上的子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

Google Chrome 5、Safari 5、Opera 10.60Firefox 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中的URL片段标识符(锚)更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆