jQuery:position() 和 offset() 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3202008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Difference between position() and offset()
提问by Svish
What is the difference between position()
and offset()
? I tried to do the following in a click event:
position()
和 和有offset()
什么区别?我尝试在点击事件中执行以下操作:
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)
而且它们似乎返回完全相同...(单击的元素位于表格中的表格单元格内)
回答by dxh
Whether they're the same depends on context.
它们是否相同取决于上下文。
position
returns a{left: x, top: y}
object relative to the offset parentoffset
returns a{left: x, top: y}
object relative to the document.
position
返回一个相对于偏移父级的{left: x, top: y}
对象offset
返回一个相对于文档的{left: x, top: y}
对象。
Obviously, if the document is the offset parent, which is often the case, these will be identical. The offset parentis "the closest positioned containing element."
显然,如果文档是偏移父级(通常是这种情况),它们将是相同的。的偏移父是“最接近的定位含有元素”。
For example, with this document:
例如,使用此文档:
<div style="position: absolute; top: 200; left: 200;">
<div id="sub"></div>
</div>
Then the $('#sub').offset()
will be {left: 200, top: 200}
, but its .position()
will be {left: 0, top: 0}
.
那么$('#sub').offset()
将会是{left: 200, top: 200}
,但它.position()
将会是{left: 0, top: 0}
。
回答by jAndy
The .offset()method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
所述.offset()方法允许我们以检索一个元素的当前位置相对于文档。将此与.position() 进行对比,后者检索相对于偏移量 parent的当前位置。当将新元素放置在现有元素之上以进行全局操作(特别是实现拖放)时,.offset() 更有用。
Source: http://api.jquery.com/offset/
回答by dwoutsourcing
Both functions return a plain object with two properties: width & height.
这两个函数都返回一个具有两个属性的普通对象:宽度和高度。
offset() refers to the position relative to the document.
position() refers to the position relative to its parent element
offset() 是指相对于文档的位置。
position() 是指相对于其父元素的位置
BUT when the object's css position is "absolute" both functions will return width=0 & height=0
但是当对象的 css 位置为“绝对”时,两个函数都将返回 width=0 & height=0