jQuery 获取元素相对于其父元素的距离
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11333647/
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
Get distance of element relative to its parent element
提问by Victor S
I would like to know how to get the distance/offset/position of an element relative to it's parent element.
我想知道如何获取元素相对于其父元素的距离/偏移量/位置。
Unlike jQuery's position()
functionality, which get's the position relative to the parent's offsetposition, I need to get the (assuming) stableposition of an element as it's distance from the top of the containing/parent element.
与position()
获取相对于父元素偏移位置的位置的jQuery功能不同,我需要获取元素的(假设)稳定位置,因为它与包含/父元素顶部的距离。
example:
例子:
<div id="parent">
<div id="pos1">Has a position of 0px from top of containing parent el.</div>
<br style="height:20px;">
<br style="height:20px;">
<div id="pos2">Has a position of 40px from top of containing parent el.</div>
</div>
So, no matter what the position of the parent element to the document, the position of pos1
and pos2
would be reported the same, as they don't change relative to their parent element...
因此,无论父元素在文档中的位置如何,pos1
和的位置pos2
都会报告相同,因为它们相对于其父元素不会发生变化......
Is this possible?
这可能吗?
回答by daniloquio
This should do it:
这应该这样做:
$('#pos1').offset().top - $('#pos1').parent().offset().top - $('#pos1').parent().scrollTop()
回答by Andamon A. Abilar
This code works for me.
这段代码对我有用。
var child_top = $("#parent_div").scrollTop() + $("#child_div").offset().top
回答by sabithpocker
Parent.offset() - child.offset() ?
Parent.offset() - child.offset() ?
Using jQuery offset()
使用 jQuery offset()