如何编写将在 URL 锚点发生任何更改时执行的 JavaScript 回调代码?
例如从http://example.com#a
到http://example.com#b
如何编写将在 URL 锚点发生任何更改时执行的 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
Google Chrome 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/。
编辑:更新浏览器支持(再次)。
我建议使用addEventListener
而不是覆盖window.onhashchange
,否则您将阻止其他插件的事件。
window.addEventListener('hashchange', function() {
...
})
看看当今全球浏览器的使用情况,不再需要回退。
从我在其他 SO 问题中看到的,唯一可行的跨浏览器解决方案是计时器。例如,看看这个问题。
setInterval()
目前只是通用解决方案。但未来有一些亮点以hashchange 事件的形式出现
(仅供记录。)YUI3“hashchange”合成事件或多或少与接受的答案相同
YUI().use('history-hash', function (Y) {
Y.on('hashchange', function (e) {
// Handle hashchange events on the current window.
}, Y.config.win);
});