offset()方法獲取或設(shè)置所選元素相對于文檔的偏移坐標。
當使用offset()方法獲取偏移量時,它將返回第一個選定元素的偏移量坐標(包含2個屬性的對象( top 和 left ))。
當使用offset()方法設(shè)置偏移量時,它將設(shè)置所有選定元素的偏移量坐標。
獲取偏移坐標:
$(selector).offset()
設(shè)置偏移量坐標:
$(selector).offset({top:value, left:value})使用函數(shù)設(shè)置偏移量坐標:
$(selector).offset(function(index, currentOffset))
獲取段落的偏移坐標:
$("button").click(function(){
let p = $("p");
let offset = p.offset();
p.html("left: " + offset.left + ", top: " + offset.top);
});測試看看?/?設(shè)置所有段落的偏移坐標:
$("button").click(function(){
$("p").offset({
top: 60,
left: 30
});
});測試看看?/?使用另一個元素的偏移量坐標設(shè)置元素的偏移量坐標:
$("button").click(function(){
$("p").offset($("div").offset());
});測試看看?/?使用函數(shù)設(shè)置偏移量坐標:
$("button").click(function(){
$("p").offset(function(i, val){
let newCord = new Object();
newCord.left = val.left + 100;
newCord.top = val.top + 100;
return newCord;
});
});測試看看?/?| 參數(shù) | 描述 |
|---|---|
| {top:value, left:value} | 指定像素的頂部和左側(cè)坐標 |
| function(index, currentOffset) | 指定一個函數(shù),該函數(shù)返回包含頂部和左側(cè)坐標的對象
|