我试图通过使用 offsetTop
属性来检测元素何时出现在容器的边界之外,但该属性没有给出我期望的结果。请参阅this simplified JSFiddle上下文。
根据MDN定义offsetTop
属性:
The HTMLElement.offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent, the closest positioned ancestor element.
在我的 JSFiddle 示例中,您可以看到 #target
元素的偏移父元素是 #container
,正如预期的那样,因为它是最近的定位祖先。然后,我期望当滚动 #container
时,target.offsetTop
的值会发生变化,因为从 #target
到顶部的距离#container
– 它的偏移父级 – 现在正在改变。然而,情况并非如此,因为当容器滚动时 target.offsetTop
根本不会改变。 (我确保示例中的文本在滚动时更新)
我对这个属性的理解有误吗?或者我做了什么导致它的工作方式与定义不同?
编辑:我确实理解错误,因为 MDN 文档(在我看来)在撰写本文时具有误导性。 MDN 文档指出 offsetTop
是相对于“offsetParent 顶部的内边框”。然而,CSS spec更准确地说,计算是相对于偏移父级的 padding-edge 完成的,而不是 MDN 定义所暗示的其 border-edge。
最佳答案
当父级滚动时,子级的 offsetTop
将保持一致,但父级的 scrollTop
将更新以反射(reflect)父级垂直滚动的像素数。实现所需行为的一个简单方法是从父级的 scrollTop
中减去子级的 offsetTop
。
请参阅此更新的 codepen 作为示例: https://jsfiddle.net/08Ltchb9/
关于html - 在滚动容器中时,元素 offsetTop 不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77275020/