获取元素相对于其父元素的距离 [英] Get distance of element relative to its parent element
问题描述
我想知道如何获取元素相对于其父元素的距离/偏移/位置.
不同于jQuery的position()
功能(相对于父元素的偏移量位置),我需要获取(假设)元素的(稳定) stable 位置距包含/父元素的顶部的距离.
示例:
<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>
因此,无论父元素在文档中的位置如何,pos1
和pos2
的位置都将报告为相同,因为它们相对于父元素不会改变... >
这可能吗?
这应该做到:
$('#pos1').offset().top - $('#pos1').parent().offset().top - $('#pos1').parent().scrollTop()
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 offset position, I need to get the (assuming) stable position of an element as it's distance from the top of the containing/parent element.
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...
Is this possible?
This should do it:
$('#pos1').offset().top - $('#pos1').parent().offset().top - $('#pos1').parent().scrollTop()
这篇关于获取元素相对于其父元素的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!