简体   繁体   English

getBoundingClientRect根据滚动位置动态更改?

[英]getBoundingClientRect changed dynamically according to scroll position?

What's wrong with below code? 下面的代码有什么问题? getBoundingClientRect value is not always the same, it changed when I fire the function after I've scrolled. getBoundingClientRect值并不总是相同,在滚动后触发函数时,它会更改。 Below function only accurate (scrolled to the correct position) if I didn't scroll the page. 如果我不滚动页面,则下面的功能仅是准确的(滚动到正确的位置)。

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

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

I didn't use scrollIntoView because I need to have an offset. 我没有使用scrollIntoView因为我需要一个偏移量。

According to MDN : 根据MDN

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport . Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。

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. 如果您需要相对于文档左上角的边界矩形,只需将当前滚动位置添加到top和left属性(可以使用window.scrollX和window.scrollY获得)即可获得一个边界矩形。与当前滚动位置无关。

So: 所以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM