很多教學都說 position() 回傳的是「相對於父元素」的偏移量,這個說法並不完全正確。真正的規則是:它會找出距離該元素最近、且有設定定位的祖先元素作為參考點;若一路都找不到,參考對象就是視窗。
$(selector).position()
回傳包含 top 與 left 兩個整數屬性的物件,同樣只對可見元素有效。
position 值為 relative、absolute 或 fixed),偏移量的參考對象為視窗。換句話說,position() 的行為比較接近 CSS 中 absolute 的定位邏輯——只是它不會真的去改你的 style。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position() 函數</title>
<style type="text/css">
* { margin:0px; padding:0px; }
.father {
background-color:green; width:200px; height:200px;
padding:50px; margin-bottom:50px; margin-left:100px;
}
.children {
height:150px; width:150px; background-color:red;
line-height:150px; text-align:center;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".children").each(function(){
var text;
text = "left:" + $(this).position().left;
text += " top:" + $(this).position().top;
$(this).text(text);
});
});
</script>
</head>
<body>
<div class="father" style="position:relative">
<div class="children"></div>
</div>
<div class="father">
<div class="children"></div>
</div>
</body>
</html>
上方那組:父元素設了 position:relative,所以子元素抓到的座標是相對於父元素的,數值會反映 50px 的 padding。
下方那組:父元素沒有任何定位設定,一路往上都找不到定位祖先,於是參考對象退回視窗,抓到的數值會把父元素的 100px 左邊距也計入。
這個範例很清楚地說明了:同樣的 HTML 結構,只差一個 position 樣式,position() 的結果就完全不同。除錯時若發現座標不如預期,第一步永遠是檢查祖先元素的定位設定。