首頁  >  文章  >  web前端  >  淺談jQuery的offset()方法及範例分享_jquery

淺談jQuery的offset()方法及範例分享_jquery

WBOY
WBOY原創
2016-05-16 15:49:57912瀏覽

offset()方法的定義與用法:

此方法傳回或設定所符合元素相對於document物件的偏移量。

語法結構一:

$(selector).offset()
取得匹配元素在目前document的相對偏移。
傳回的物件包含兩個整數屬:top和left。
此方法只對可見元素有效。
實例代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">

<style type="text/css">
*{
 margin:0px;
 padding:0px;
}
.father{
 border:1px solid black;
 width:400px;
 height:300px;
 padding:10px;
 margin:50px;
}
.children{
 height:150px;
 width:200px;
 margin-left:50px;
 background-color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $("button").click(function(){
   a=$(".children").offset();
   alert("元素的偏移量坐标是:"+a.top+"|"+a.left+"");
  })
})
</script>
</head>
<body>
<div class="father">
 <div class="children"></div>
</div>
<button>获取元素的坐标</button>
</body>
</html>

以上程式碼可以彈出子div相對於document的偏移量。

語法結構二:

$(selector).offset(value)

設定匹配元素相對於document物件的座標。
offset()方法可以讓我們重新設定元素的位置。這個元素的位置是相對於document物件的。
如果物件原先的position樣式屬性是static的話,會被改成relative來實現重定位。
參數列表:

參數 描述
value 規定以像素計的 top 和 left 座標。

可能的值:

1.值對,如 {top:200,left:10}。
2.帶有top和left 屬性的物件。

實例碼:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">

<style type="text/css">
.father{
 border:1px solid black;
 width:400px;
 height:300px;
}
.children{
 height:150px;
 width:200px;
 background-color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $("button").click(function(){
  $(".children").offset({top:100,left:100})
 })
})
</script>
</head>
<body>
<div class="father">
 <div class="children"></div>
</div>
<button>点击设置偏移量</button>
</body>
</html>

以上程式碼可以設定div相對於document的偏移量。

語法結構三:

使用函數的回傳值來設定偏移座標:

$(selector).offset(function(index,oldoffset))
參數列表:

參數 描述
function(index,oldvalue) 規定傳回被選元素新偏移座標的函數:
index - 可選。元素的索引。
oldvalue - 可選。當前座標。

實例碼:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<style type="text/css">
.father{
 border:1px solid black;
 width:400px;
 height:300px;
}
.children{
 height:150px;
 width:200px;
 background-color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $("button").click(function(){
  $(".children").offset(function(a,b){
   var newpoint= new Object();
   newpoint.top=b.top+50;
   newpoint.left=b.left+50;
   return newpoint;
  })
 })
})
</script>
</head>
<body>
<div class="father">
 <div class="children"></div>
</div>
<button>点击设置偏移量</button>
</body>
</html>

以上程式碼同樣可以設定元素的偏移,不過值是透過函數傳回。

以上所述就是本文的全部內容了,希望大家能夠喜歡。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn