jQuery的位置方法问题

时间:2011-08-10 07:48:02

标签: javascript jquery

如果我有以下标记:

<div id="parent" style="width: 300px; height: 300px;">
  <div id="child" style="position: relative; left: 0; top: 0; width: 100px; height: 100px;"></div>
</div>

我希望得到孩子相对于其父母的位置,唯一的方法如下:?

x = parseInt($('#child').css('left')); // returns 0 as needed
y = parseInt($('#child').css('top')); // return 0 as needed

因为如果我执行以下操作:

x = $('#child').position().left; // most likely will not return 0 
y = $('#child').position().top; // most likely will not return 0

这个位置是错误的,因为偏移方法也会添加祖父母的边距,填充和边框(无论是具有默认边距的身体元素还是任何其他祖父母元素)。

我需要获得正确的位置(在我的示例中它将是0, 0)但是我怀疑jQuery中没有可以为我计算它的方法?

2 个答案:

答案 0 :(得分:7)

.position()是正确的。它会为您提供相对于元素的偏移父级的xy值。您的#child元素相对于其自己的偏移父项定位,即<body>。要使#parent为其偏移父级,请为其positionrelative提供absolute

<div id="parent" style="position: relative; width: 300px; height: 300px;">
    <div id="child" style="position: relative; left: 0; top: 0;...;"></div>
</div>

答案 1 :(得分:3)

.position()方法允许我们检索元素相对于偏移父元素的当前位置。将此与.offset()进行对比,后者检索相对于文档的当前位置。 使用.offset()

相关问题