处理js中的URL锚点更改事件 [英] Handle URL anchor change event in js
问题描述
如何编写将在URL锚点中的任何更改执行的JavaScript回调代码?
How can I write the JavaScript callback code that will be executed on any changes in the URL anchor?
例如从 http://example.com#a http:/ /example.com#b
推荐答案
Google自定义搜索引擎使用计时器根据先前的值检查哈希值,而单独域上的子iframe更新父代的位置哈希值以包含iframe文档的正文大小。当定时器捕获更改时,父级可以调整iframe的大小以匹配身体的大小,以便不显示滚动条。
Google Custom Search Engines use a timer to check the hash against a previous value, whilst the child iframe on a seperate domain updates the parent's location hash to contain the size of the iframe document's body. When the timer catches the change, the parent can resize the iframe to match that of the body so that scrollbars aren't displayed.
以下内容实现相同:
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
事件:
Google Chrome 5, Safari 5, Opera 10.60, Firefox 3.6 and Internet Explorer 8 all support the hashchange
event:
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/。
jQuery also has a plugin that will check for the hashchange event and provide its own if necessary - http://benalman.com/projects/jquery-hashchange-plugin/.
编辑:更新了浏览器支持(再次)。
EDIT: Updated browser support (again).
这篇关于处理js中的URL锚点更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!