一、語法
1、 返回偏移座標
$(selector).offset();
top: $(selector).offset().top;
left: $(selector).offset().left;
2、設置偏移座標:
$(selector).offset({top:value,left:value});
參數的含義:{top:value,left:value} 當設置偏移時是必需的。規定以像素爲單位的 top 和 left 座標。
可能的值:(1)、名/值對,比如 {top:100,left:100} , (2)、一個帶有 top 和 left 的對象(實例)
3、使用函數設置偏移座標:
$(selector).offset(function(index,currentoffset));
可選。規定返回包含 top 和 left 座標的對象的函數。
index - 返回集合中元素的 index 位置。
currentoffset - 返回被選元素的當前座標。
二、offset 的定義和用法
offset() 方法設置或返回被選元素 相對於文檔的偏移座標
1、當用於返回偏移時:
該方法返回第一個匹配元素的偏移座標,它返回一個帶有2個屬性( 以像素爲單位的 top 和 left 位置)的對象
2、當用於設置偏移時:
該方法設置所有匹配元素的偏移座標,
三、實例
<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
名/值 對
$("button").click(function(){
$("p").offset({top:200,left:200});
});
對象
$("button").click(function(){
newPos=new Object();
newPos.left="0";
newPos.top="100";
$("p").offset(newPos);
});
函數
$("p").offset(function(n,c){
newPos=new Object();
newPos.left=c.left+100;
newPos.top=c.top+100;
return newPos;
});
});
</script>
</head>
<body>
<p style="border:1px solid red">This is a paragraph.</p>
<button>Set the offset coordinates of the p element</button>
</body>
</html>
四、注意事項
offset() 方法 返回的top , left. 跟 margin-top,margin-left 也有關係。
如果元素有margin-top,margin-left. 它獲取當前的margin. 沒有則是默認取值。
如果父元素也有margin,broder 的話。它也會受到影響。取值要更大。 因爲offset() 取的當前與文檔的偏移座標。