回答

117

谷歌自定義搜索引擎使用定時器來確認散列與先前值,同時在一個單獨的域孩子的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 

谷歌的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/

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

+0

爲了完整性,將'var storedHash = window.location.hash;'添加到放置在一起的彙總塊中。順便說一句:現在這被稱爲polyfill我認爲。 – 2013-03-31 14:58:36

+1

現在,你可以在'window'上監聽'hashChange' http://stackoverflow.com/questions/6390341/how-to-detect-url-change – 2013-10-08 19:55:33

+2

@Timo:你......沒看過我的答案,你是否? :-P – 2013-10-08 22:14:47

2

從我在其他的做題看,唯一可行的跨瀏覽器的解決方案是一個計時器。例如,請查看this question

-1

你可以從這個

Mutation event types

突變事件模塊設計 允許任何變化 到文檔的結構, 包括ATTR和文字的修改通知獲得更多的信息。

+0

這是關於DOM變化。 – rsman 2017-09-20 12:11:32

3

setInterval()是目前唯一的通用解決方案。但也有在未來的一段光的hashchange event

+0

供參考:'onhashchange'事件[Mozilla開發者網絡文檔](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange) – 2015-05-28 05:15:21

1

形式(只是爲了記錄。)的YUI3「hashchange」合成事件做更多的還是同樣的事情少爲接受的答案

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