滚动时JavaScript getBoundingClientRect()会发生变化 [英] JavaScript getBoundingClientRect() changes while scrolling
问题描述
我想要一个元素的Y坐标与Y值= 0之间的确切距离,我认为它是文档的顶部。
I want to have the exact distance between the Y-coordinate of an element an the Y-value=0, which I consider as the top of the document.
myElement.getBoundingClientRect().top;
但是滚动时getBoundingClientRect()的值似乎发生了变化。如何获得myElement与Y坐标= 0(文档顶部)之间的实际距离?
But the value of getBoundingClientRect() seems to change while scrolling. How can I get the real distance between myElement and the Y-coordinate=0 (top of document)?
推荐答案
这是因为 getBoundingClientRect()
获取与窗口相关的值
(仅限页面的当前可见部分),而不是 document
(整页)。
因此,在计算其值时也会考虑滚动
基本上, document = window + scroll
It is because getBoundingClientRect()
gets values with respect to the window
(only the current visible portion of the page), not the document
(whole page).
Hence, it also takes scrolling into account when calculating its values
Basically, document = window + scroll
因此,要获得myElement和Y坐标之间的距离= 0(顶部文件),你也可以添加垂直滚动的值:
So, to get the distance between myElement and the Y-coordinate=0 (top of document), you would have add the value of vertical-scroll also:
myElement.getBoundingClientRect()。top + window.scrollY ;
来源: https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
这篇关于滚动时JavaScript getBoundingClientRect()会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!