是否有在浏览器滚动到命名锚点时触发的事件

Is there an event that fires when a browser scrolls to a named anchor?

本文关键字:事件 浏览器 滚动 是否      更新时间:2023-09-26

>当使用命名锚点链接到页面时,例如 page.html#heading浏览器将加载页面,然后向下跳转到锚点。是否有浏览器事件在完成此操作时触发?

为了解释我背后的原因:我想使用该事件在浏览器中触发动画。

更改哈希会触发hashchange事件。

但是,我认为在加载链接已经设置了哈希的 url 时不会触发。但是,如果您希望某个脚本根据哈希运行,则可以在页面加载时检查哈希(location.hash(。

在 Mac 上的 Safari 7.0.3 中,这有效...

HTML 具有:

<a id="jumper" href="#aa">Jump</a>

.JS:

<script>
var j = document.getElementById("jumper");
j.addEventListener("click", registerAnchorJump);
function registerAnchorJump(e) {
    window.addEventListener("scroll", unregisterAnchorJump);
}
function unregisterAnchorJump(e) {
    // trigger your animation...
    console.log(window.scrollY);
    window.removeEventListener("scroll",unregisterAnchorJump);
}
</script>

花哨的步法,以防止在用户正常滚动窗口时不断触发滚动事件。