offset()方法获取或设置所选元素相对于文档的偏移坐标。
当使用offset()方法获取偏移量时,它将返回第一个选定元素的偏移量坐标(包含2个属性的对象( top 和 left ))。
当使用offset()方法设置偏移量时,它将设置所有选定元素的偏移量坐标。
获取偏移坐标:
$(selector).offset()
设置偏移量坐标:
$(selector).offset({top:value, left:value})使用函数设置偏移量坐标:
$(selector).offset(function(index, currentOffset))
获取段落的偏移坐标:
$("button").click(function(){
let p = $("p");
let offset = p.offset();
p.html("left: " + offset.left + ", top: " + offset.top);
});测试看看‹/›设置所有段落的偏移坐标:
$("button").click(function(){
$("p").offset({
top: 60,
left: 30
});
});测试看看‹/›使用另一个元素的偏移量坐标设置元素的偏移量坐标:
$("button").click(function(){
$("p").offset($("div").offset());
});测试看看‹/›使用函数设置偏移量坐标:
$("button").click(function(){
$("p").offset(function(i, val){
let newCord = new Object();
newCord.left = val.left + 100;
newCord.top = val.top + 100;
return newCord;
});
});测试看看‹/›| 参数 | 描述 |
|---|---|
| {top:value, left:value} | 指定像素的顶部和左侧坐标 |
| function(index, currentOffset) | 指定一个函数,该函数返回包含顶部和左侧坐标的对象
|