此方法返回或設定所匹配元素相對於document物件的偏移量。
語法結構一:
複製程式碼 程式碼如下:$(selector)et()
獲取匹配元素在當前document的相對偏移。
返回的物件包含兩個整型屬:top和left。
此方法只對可見元素有效。
例項程式碼:
複製程式碼 程式碼如下:
*{
margin:0px;
padding:0px;
}
er{
border:1px solid black;
width:400px;
height:300px;
padding:10px;
margin:50px;
}
dren{
height:150px;
width:200px;
margin-left:50px;
background-color:green;
}
$(document)y(function(){
$("button")k(function(){
a=$("dren")et();
alert("元素的偏移量座標是:"++"|"++"");
})
})
獲取元素的座標
以上程式碼可以彈出子div相對於document的偏移量。
語法結構二:
複製程式碼 程式碼如下:$(selector)et(value)
設定匹配元素相對於document物件的座標。
offset()方法可以讓我們重新設定元素的位置。這個元素的位置是相對於document物件的。
如果物件原先的position樣式屬性是static的'話,會被改成relative來實現重定位。
引數列表:
引數 描述 value 規定以畫素計的 top 和 left 座標。
可能的值:
1.值對,比如 {top:200,left:10}。
2.帶有top和left 屬性的物件。
例項程式碼:
複製程式碼 程式碼如下:
er{
border:1px solid black;
width:400px;
height:300px;
}
dren{
height:150px;
width:200px;
background-color:green;
}
$(document)y(function(){
$("button")k(function(){
$("dren")et({top:100,left:100})
})
})
點選設定偏移量
以上程式碼可以設定div相對於document的偏移量。
語法結構三:
使用函式的返回值來設定偏移座標:
複製程式碼 程式碼如下:$(selector)et(function(index,oldoffset))
引數列表:
引數 描述 function(index,oldvalue) 規定返回被選元素新偏移座標的函式:
index - 可選。元素的索引。
oldvalue - 可選。當前座標。
例項程式碼:
複製程式碼 程式碼如下:
er{
border:1px solid black;
width:400px;
height:300px;
}
dren{
height:150px;
width:200px;
background-color:green;
}
$(document)y(function(){
$("button")k(function(){
$("dren")et(function(a,b){
var newpoint= new Object();
=+50;
=+50;
return newpoint;
})
})
})
點選設定偏移量
以上程式碼同樣可以設定元素的偏移,不過值是通過函式返回。