gpt4 book ai didi

javascript - 如何获得一致的 ScrollIntoView 行为

转载 作者:行者123 更新时间:2023-11-29 15:29:47 25 4
gpt4 key购买 nike

所以我一直在使用 ScrollIntoView() 跳转到 react 组件中的 anchor 作为网络应用程序的一部分。对于小页面,它工作正常,到达正确的位置并且表现得像人们期望的那样。我有一个较大的页面,其中的行为很奇怪。加载时, anchor 的跳转低于应有的位置半页或更多。第一次点击指向任何 anchor 的链接时,包括同一个 anchor , anchor 最终会比它应该位于的位置高出类似的数量。只要不重新加载页面,此后的每次后续点击都可以完美运行。这是我的函数代码。它有一个setTimeout,因为我认为问题与页面加载有关,但没有效果。这是我的功能:

scrollToAnchor: function () {
let anchorName = this.props.location.hash || window.location.hash;
if (anchorName) {
anchorName = anchorName.replace("#", "");
let anchorElement = document.getElementById(anchorName);
if (anchorElement) {
window.setTimeout(anchorElement.scrollIntoView(true), 0);
}
} else {
window.scrollTo(0, 0);
}
},

最佳答案

在我的例子中,我必须手动添加默认参数才能使其在某些浏览器中工作。 blockinline 参数有一个关联的默认值,但我必须像这样手动输入它们:

my_element.scrollIntoView(
{ behavior: 'smooth' , block: 'start', inline: 'nearest'}
);

一旦我在 scrollIntoViewOptions 中定义了它们, 它在所有浏览器上都运行良好。

PS:不要忘记 polyfill平滑滚动。

关于javascript - 如何获得一致的 ScrollIntoView 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35854573/

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