如何编写将在 URL 片段标识符( anchor )发生任何更改时执行的 Javascript 回调代码?
例如从http://example.com#a
到http://example.com#b
最佳答案
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
谷歌浏览器 5、Safari 5、Opera 10.60 , Firefox 3.6和 Internet 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 - 在 Javascript 中处理 URL 片段标识符( anchor )更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161906/