簡體   English   中英

"處理 Javascript 中的 URL 片段標識符(錨點)更改事件"

[英]Handle URL fragment identifier (anchor) change event in Javascript

如何編寫將在 URL 片段標識符(錨點)的任何更改上執行的 Javascript 回調代碼?

例如從http:\/\/example.com#a<\/code>到http:\/\/example.com#b<\/code>

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

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/

編輯 :更新瀏覽器支持(再次)。

setInterval()現在只是通用解決方案。 但是將來會以hashchange事件的形式出現一些亮點

從我在其他SO問題中看到的,唯一可行的跨瀏覽器解決方案是計時器。 這個問題為例。

我建議使用addEventListener而不是覆蓋window.onhashchange ,否則你將阻止其他插件的事件。

window.addEventListener('hashchange', function() {
...
})

看看今天的全球瀏覽器使用情況,不再需要回退。

(僅供記錄。)YUI3“hashchange”合成事件或多或少與接受的答案相同

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

這是一個簡單的方法,對我來說很好用 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);
});

希望對你有效。

您可以從中獲得更多信息

突變事件類型

突變事件模塊旨在允許通知文檔結構的任何更改,包括attr和文本修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM