gpt4 book ai didi

javascript - anchor 链接偏移仅在第一次单击时不起作用

转载 作者:行者123 更新时间:2023-12-02 14:04:03 25 4
gpt4 key购买 nike

下面是我的JS代码。我有一个带有滚动 anchor 链接的页面。我需要用户在单击链接时转到页面上的特定部分,而不覆盖该部分的基本标题。

这就是我已经能够完成的事情(当然,在 Stackoverlfow 调查的帮助下)。

// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).

上面的代码似乎有效,但问题是它仅在我第二次单击任何 anchor 时才有效。为什么它不会在第一条领带上触发?我知道它与 hashchange 有关,因此 javascript 从第二个链接开始只是因为存在 hashchange。你能给我一个解决方案吗?

最佳答案

window.onload = function () {
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and m
};
<a href="#hello">Hello</a>
<div style="height: 300px;background:#ccc">spacer</div>
<div id="hello">Hello there!</div>
<div style="height: 300px;background:#ccc">spacer</div>

希望这有帮助

关于javascript - anchor 链接偏移仅在第一次单击时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40179520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com