回答

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); 
});