position()方法的定義和用法:
此方法獲取匹配元素相對某些元素的偏移量。
返回的對象包含兩個整型屬性(top和left)的對象。
此方法只對可見元素有效。
語法結構:
$(selector).position()
在教程的開頭之所以說是獲取匹配元素相對於某些元素的偏移量。很多教程都說方法返回的偏移量是相對於父元素,其實並非完全如此,此方法會將匹配元素以絕對定位方式處理,當然並不是說真的將匹配元素設置為絕對定位。方法的偏移量參考原則如下:
1.如果父輩元素中沒有采用定位的(position屬性值為relative、absolute或者fixed),那麼偏移量參考對象為窗口。
2.如果父輩元素中有采用定位的,那麼偏移量的參考對象為距離它最近的采用定位的元素,
實例代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<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>
在以上代碼中頂部組合,由於父元素采用的是相對定位,那麼獲取的偏移量就是相對於父元素的。在底部的組合中,由於父元素沒有采用定位,那麼偏移量參考對象就是窗口。
以上所述就是本文的全部內容了,希望大家能夠喜歡。