Handle URL anchor change event in js(处理 js 中的 URL 锚点更改事件)
问题描述
如何编写将在 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.
类似下面的东西可以达到同样的效果:
Something like the following achieves the same:
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 all 支持 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 锚点更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理 js 中的 URL 锚点更改事件


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01