gpt4 book ai didi

javascript - getBoundingClientRect 根据滚动位置动态变化?

转载 作者:行者123 更新时间:2023-11-28 03:37:19 31 4
gpt4 key购买 nike

下面的代码有什么问题吗? getBoundingClientRect 值并不总是相同,当我滚动后触发该函数时它会发生变化。如果我没有滚动页面,下面的函数才准确(滚动到正确的位置)。

scrollToTargetAdjusted() {
const element = document.getElementById('myDiv')
const dockingElementOffset = 80
const elementPosition = element.getBoundingClientRect().top
const offsetPosition = elementPosition - dockingElementOffset

window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
})
}

我没有使用 scrollIntoView 因为我需要一个偏移量。

最佳答案

根据MDN :

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. This means that the rectangle's boundary edges (top, right, bottom, left) change their values every time the scrolling position changes (because their values are relative to the viewport and not absolute).

If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position.

所以:

window.scrollTo({
top: offsetPosition + // based on getBoundingClientRect().top
window.scrollY,
behavior: 'smooth'
})

关于javascript - getBoundingClientRect 根据滚动位置动态变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57587061/

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