offsetParent和parentElement或parentNode之间的差异 [英] Difference between offsetParent and parentElement or parentNode
问题描述
我有一个以下DOM结构
I have a following DOM structure
<body>
<div>
<table>
<outerElement>
<innerElement />
</outerElement>
<table>
</div>
</body>
DIV将其溢出设置为auto,如果表增长更大 - 它会在DIV中滚动。
DIV has it's overflow set to auto so if table grows bigger - it scrolls within the DIV.
在这种情况下,为什么 table.offsetParent
返回正文,而 table.parentNode
和 parentElement
返回Div?
In this scenario why table.offsetParent
returns the body while both table.parentNode
and parentElement
return the Div?
我需要计算 innerElement
在窗口中,所以我通过所有父元素遍历,收集他们的 offsetTop
和 offsetLeft
值。直到DIV offsetParent
正常工作,然后直接跳到正文。如果在某些时候卷动有问题,我需要考虑 scrollTop
和 scrollLeft
,就像在DIV在上面的例子中。问题是如果我使用 offsetParent
我从来没有遇到DIV作为父母之一。
I need to calculate current position of the innerElement
within the window, so I traverse from it up thru all parent elements, collecting their offsetTop
and offsetLeft
values. Up until the DIV offsetParent
works fine and then it skips it directly to the body. The problem if there's scrolling involved at some point, I need to account for scrollTop
and scrollLeft
as well - like in the DIV in the above example. The problem is if I use offsetParent
I never encounter the DIV as one of the parents.
更新
这是执行遍历的代码的一部分:
This is part of the code that does the traversing:
while (oElem && getStyle(oElem, 'position') != 'absolute' && getStyle(oElem, 'position') != 'relative') {
curleft += oElem.offsetLeft;
curtop += oElem.offsetTop;
oElem = oElem.offsetParent;
}
其中 getStyle
推荐答案
清除 offsetParent
,你必须添加许多黑客和支票,以确保你正确的。
Stay clear of offsetParent
, you'll have to add lots of hacks and checks to ensure you get it right.
尝试使用 getBoundingClientRect 。
这篇关于offsetParent和parentElement或parentNode之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!