offset() 回傳或設定符合元素「相對於 document」的偏移量,是處理浮動層定位、拖曳功能時的基礎工具。它有三種呼叫形式,分別負責讀取、直接設定、以及用函式計算後設定。
$(selector).offset()
回傳一個物件,包含 top 與 left 兩個整數屬性。要注意:此方法只對可見元素有效,display:none 的元素會拿到 0。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>offset() 函數</title>
<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 相對於整個文件的座標,數值會包含父層的 margin 與 padding 影響。
$(selector).offset(value)
參數 value 規定以像素計的 top 與 left 座標,可以是值對(如 {top:200, left:10}),也可以是帶有 top、left 屬性的物件。
一個重要行為:若元素原本的 position 樣式是 static,jQuery 會把它改成 relative 才能完成重新定位。
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".children").offset({top:100, left:100})
});
});
</script>
$(selector).offset(function(index, oldoffset))
函式參數 index 是元素索引,oldoffset 是目前座標。適合要「在現有位置上做位移」的場景。
<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>
每次點擊,子元素都會在原位置上往右下各挪 50 像素,示範了「相對位移」的寫法。
offset() 的參考原點固定是文件;position() 的參考原點則是最近的定位祖先元素(或視窗)。選錯方法會導致座標對不上,這是初學者最常遇到的問題。