jQuery offset() 方法
实例
返回 <p> 元素的偏移坐标:
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script><script>$(document).ready(function(){$("button").click(function(){var x = $("p").offset();alert("Top: " + x.top + " Left: " + x.left);});});</script></head><body><p>这是一个段落</p><button>返回 p 元素的偏移坐标</button></body></html>
定义与用法
offset() 方法设置或返回所选元素相对于文档的偏移坐标。
当用于返回偏移量时:
此方法返回第一个匹配元素的偏移坐标。它返回一个具有两个属性的对象;以像素为单位的 top(顶部)和(left)左侧位置。
当用于设置偏移量时:
该方法设置所有匹配元素的偏移坐标。
语法
返回偏移坐标:
$(selector).offset()
设置偏移坐标:
$(selector).offset({top:value,left:value})
使用函数设置偏移坐标:
$(selector).offset(function(index,currentoffset))
| 参数 | 描述 |
|---|---|
| {top:value,left:value} | 必填。 设置偏移时。以像素为单位指定顶部和左侧坐标 值可以为:
|
| function(index,currentoffset) | 可选。 指定一个函数,该函数返回包含顶部和左侧坐标的对象
|