jQuery:position()和offset()之间的区别 [英] jQuery: Difference between position() and offset()
问题描述
position()
和offset()
有什么区别?我试图在点击事件中执行以下操作:
What is the difference between position()
and offset()
? I tried to do the following in a click event:
console.info($(this).position(), $(this).offset());
它们似乎返回完全相同的...(单击的元素在表的表单元格之内)
And they seem to return exactly the same... (The clicked element is within a table cell in a table)
推荐答案
是否相同取决于上下文.
Whether they're the same depends on context.
-
position
返回相对于偏移父级的{left: x, top: y}
对象
position
returns a{left: x, top: y}
object relative to the offset parent
offset
返回相对于文档的
offset
returns a {left: x, top: y}
object relative to the document.
很明显,如果文档是偏移父级(通常是这种情况),则它们将是相同的. 偏移父级是包含元素的最接近位置."
Obviously, if the document is the offset parent, which is often the case, these will be identical. The offset parent is "the closest positioned containing element."
例如,使用此文档:
<div style="position: absolute; top: 200; left: 200;">
<div id="sub"></div>
</div>
然后$('#sub').offset()
将是{left: 200, top: 200}
,但其.position()
将是{left: 0, top: 0}
.
这篇关于jQuery:position()和offset()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!