2011-08-10 16 views
5

如果我有以下標記: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

注意:如果未指定明確的頂部,$('#child').css('top')可以給出「自動」。 –

回答

7

.position()是正確的。它會給你xy相對於元素的偏移父值。您的#child元素相對於其自己的抵消父級定位,即<body>。爲了使#parent抵消父母,給它positionrelativeabsolute

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

.position()方法允許我們檢索元素相對於偏移父級的當前位置。將它與.offset()進行對比,該文件檢索相對於文檔的當前位置。 使用.offset()