jQuery中position()方法用法執行個體,jqueryposition

來源:互聯網
上載者:User

jQuery中position()方法用法執行個體,jqueryposition

本文執行個體講述了jQuery中position()方法用法。分享給大家供大家參考。具體分析如下:

此方法擷取匹配元素相對某些元素的位移量。
返回的對象包含兩個整型屬性(top和left)的對象。
此方法只對可見元素有效。
文法結構:
複製代碼 代碼如下:$(selector).position()

在教程的開頭之所以說是擷取匹配元素相對於某些元素的位移量。很多教程都說方法返回的位移量是相對於父元素,其實並非完全如此,此方法會將匹配元素以絕對位置方式處理,當然並不是說真的將匹配元素設定為絕對位置。方法的位移量參考原則如下:

1.如果父輩元素中沒有採用定位的(position屬性值為relative、absolute或者fixed),那麼位移量參考對象為視窗。
2.如果父輩元素中有採用定位的,那麼位移量的參考對象為距離它最近的採用定位的元素.

執行個體代碼:

複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.bkjia.com/" />
<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>

在以上代碼中頂部組合,由於父元素採用的是相對定位,那麼擷取的位移量就是相對於父元素的。在底部的組合中,由於父元素沒有採用定位,那麼位移量參考對象就是視窗。

希望本文所述對大家的jQuery程式設計有所協助。

本文

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.