2011-08-10 44 views
0

爲什麼position方法不是在這種情況下返回[left: 100, top: 10]爲什麼position方法不會返回期望值?

<!DOCTYPE HTML> 
<html> 
<head> 
<style> 
#parent1 { 
    width: 300px; 
    height: 200px; 
    border: solid 9px pink; 
} 

#child1 { 
    position: relative; 
    left: 100px; 
    top: 10px; 
    width: 100px; 
    height: 100px; 
    border: solid 5px green; 
} 
</style> 
<script src="http://jquery-local/jquery.all.js"></script> 
<script type="text/javascript"> 
(function ($) { 
    $(document).ready(function() { 
     console.log($('#child1').position()); 
    }); 
})(jQuery); 
</script> 
</head> 
<body> 

<div id="parent1"> 
    <div id="child1"></div> 
</div> 

</body> 
</html> 

是獲得通過css方法的位置的唯一途徑?

+1

它會返回什麼? –

回答

0

對我的作品 - 在this JSFiddle,我得到

left: 119 
top: 19 

佔了10px的最高值加上週圍元素的9px邊框。

position()可能不是你想要的東西,雖然 - 它檢索位置relative to the offset parent.在這種情況下,它不會有所作爲,因爲沒有偏移父母,但如果你想在文檔,使用位置代替.offset()

0

對我而言,它返回:[117,27]。

首先,因爲孩子的位置是相對於父母的,所以孩子的座標只與父母的座標相對。這意味着父母的任何定位(例如默認身體邊距)都會添加到孩子的位置。此外,還添加了另一個9像素的父級邊框。如果您將身體的邊距設置爲0,那麼孩子的位置是[109,19] :)

相關問題