在 Javascript 中处理 URL 片段标识符(锚点)更改事件

发布于 2024-08-19 10:29:01 字数 135 浏览 7 评论 0 原文

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

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

How can I write the Javascript callback code that will be executed on any changes in the URL fragment identifier (anchor)?

For example from http://example.com#a to http://example.com#b

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

何以心动 2024-08-26 10:29:01

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

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/

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

Google Custom Search Engines use a timer to check the hash against a previous value, whilst the child iframe on a seperate domain updates the parent's location hash to contain the size of the iframe document's body. When the timer catches the change, the parent can resize the iframe to match that of the body so that scrollbars aren't displayed.

Something like the following achieves the same:

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.60, Firefox 3.6 and Internet Explorer 8 all support the hashchange event:

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

and putting it together:

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 also has a plugin that will check for the hashchange event and provide its own if necessary - http://benalman.com/projects/jquery-hashchange-plugin/.

EDIT: Updated browser support (again).

趴在窗边数星星i 2024-08-26 10:29:01

可以为 hashchange 事件,每当片段标识符发生变化时都会触发该事件:

window.addEventListener('hashchange', function() {
  // Perform action
  // [...]
})

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

纵观当今全球浏览器的使用情况,不再需要回退,因为现代浏览器支持此事件。

An event listener can be added for the hashchange event, which will fire whenever the fragment identifier changes:

window.addEventListener('hashchange', function() {
  // Perform action
  // [...]
})

I would recommend this approach instead of overwriting window.onhashchange, otherwise you will block the event for other plugins.

Looking at the global browser usage today, a fallback is longer needed, as modern browsers support this event.

污味仙女 2024-08-26 10:29:01

从我在其他问题中看到的,唯一可行的跨浏览器解决方案是计时器。例如,查看这个问题

From what I see in other SO questions, the only workable cross-browser solution is a timer. Check out this question for example.

热风软妹 2024-08-26 10:29:01

setInterval() 目前是唯一的通用解决方案。但未来会有一些亮点,形式为 hashchange 事件

setInterval() is only universal solution for now. But there are some light in the future in form of hashchange event

番薯 2024-08-26 10:29:01

(仅供记录。)YUI3“hashchange”合成事件或多或少与接受的答案相同

YUI().use('history-hash', function (Y) {
  Y.on('hashchange', function (e) {
    // Handle hashchange events on the current window.
  }, Y.config.win);
});

(Just for the record.) The YUI3 "hashchange" synthetic event does more or less the same thing as the accepted answer

YUI().use('history-hash', function (Y) {
  Y.on('hashchange', function (e) {
    // Handle hashchange events on the current window.
  }, Y.config.win);
});
笑忘罢 2024-08-26 10:29:01

这是一个简单的方法,对我来说用 jQuery 效果很好。
我还添加了一个动画来滚动到锚元素:

$(window).on('hashchange', function(e){
     var origEvent = e.originalEvent;
         var elementToBeClicked = $('a[href^="'+window.location.hash+'"]').click();  
        $([document.documentElement, document.body]).animate({
        scrollTop: 200
    }, 100);
});

希望它对您有用。

Here's a simple way that worked just fine for me with jQuery.
I've added a animation to scroll to the anchor element aswell:

$(window).on('hashchange', function(e){
     var origEvent = e.originalEvent;
         var elementToBeClicked = $('a[href^="'+window.location.hash+'"]').click();  
        $([document.documentElement, document.body]).animate({
        scrollTop: 200
    }, 100);
});

Hope it works for you.

酒中人 2024-08-26 10:29:01

您可以从此

突变 获取更多信息事件类型

突变事件模块设计
允许通知任何更改
到文档的结构,
包括属性和文本修改。

You can get more info from this

Mutation event types

The mutation event module is designed
to allow notification of any changes
to the structure of a document,
including attr and text modifications.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文