如何在jQuery中相对于父级获取offset()? [英] How to get offset() relative to parent in jQuery?
问题描述
这使我可以从主窗口的左边缘找到某些元素的位置:
This gives me the position of some element from the left edge of the main window:
$('#bar').offset().left;
如果该元素位于其他元素内,并且我想要#bar相对于#foo(它是父级)的位置,那我该怎么办呢?
If that element is situated inside some other element and I wanted the position of #bar relative to #foo (it's parent), how can I get that?
<style>
#foo { width: 200px; margin: 0 auto; }
#foo #bar { width: 50px; margin: 0 auto; }
</style>
<div id="foo">
<span id="bar"></span>
</div>
我看到有一个名为offsetParent()
的函数,但是在控制台登录时,该函数似乎没有任何名为left
或x
的属性.因此,不确定是否可以用来获取我需要的东西.
I saw that there is a function called offsetParent()
but when console logged it doesn't seem like this function has any properties called left
or x
. So not sure if that can be used to get what I need.
因此在上面的示例中,偏移量应距父对象边缘约125像素,而不是距主窗口边缘约数千个像素.
So in my example above the offset should be something around 125px from the parent's edge rather than some thousands of pixels from the main windows edge.
推荐答案
使用position()方法.
Use the position() method.
$('#bar').position().left;
这篇关于如何在jQuery中相对于父级获取offset()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!