在匹配的元素集中,获取第一个元素的当前坐标,或者设置每一个元素的坐标,坐标相对于文档
内容:
- .offset()
- .offset()
- .offset( coordinates )
- .offset( coordinates )
- .offset( function(index, coords) )
.offset() 返回对象
描述:在匹配的元素集中,取得第一个元素相对于文档的坐标
.offset() 添加于version 1.2
这个方法不接受任何参数
.offset()方法允许我们检索一个元素当前相对于文档的坐标,与.position()不同的是,.position()方法检索元素当前相对于父级元素的偏移
当通过全局操作(特别是拖拽)将一个元素定位到已经存在的一个元素上时,.offset()更有用。
.offset()返回一个包行top 和left属性的对象
注意:jQuery不支持取得隐藏元素的偏移坐标,同样地,也无法取得元素的borders, margins, padding信息
若元素的属性设置为visibility:hidden,我们依然可以取得它的位置信息,但是属性为display:none的元素不包括在内,因为在绘 制DOM树的时候它们根本没有绘制,所以返回的位置信息是undefined
更多注意:和尺寸相关的API,包括.offsert(),返回的数字在某些情况下可能是分数,我们不能假定它是整数。相同的,当网页被用户或浏览器放大,返回的尺寸可能不准确,不要只当API可以检测这种情况。
例子:
例子:取得第二个段落的偏移
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left:10px;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
var p = $("p:last");
var offset = p.offset();
p.html("left: " + offset.left + ", top: " + offset.top);
</script>
</body>
</html>
(译注:由于博客内不能运行代码,所以翻译时均通过截图来看到效果,有交互时,附上文字说明)
例子:点击查看偏移量
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left:10px;
color:blue;
width:200px;
cursor:pointer;
}
span {
color:red;
cursor:pointer;
}
div.abs {
height:50px;
width:50px;
position:absolute;
left:220px;
top:35px;
background-color:green;
cursor:pointer;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="result">Click an element</div>
<p>This is the best way to <span>find</span> an offset.</p>
<div class="abs"></div>
<script>
$("*", document.body).click(function(event) {
var offset = $(this).offset();
event.stopPropagation();
$("#result").text( this.tagName + " coords ( " + offset.left + ", " + offset.top + " )" );
});
</script>
</body>
</html>
(译注:DIV coords(220,35)处原来是Click an element,当点击文档中的任意元素,其变化点击元素的标签名+坐标值)
.offset(coordinates) 返回:jQuery
描述:设置匹配集中每一个元素的当前坐标,坐标相对于文档
.offset(coordinates) 添加于version 1.4
coordinates
类型:
PainObject
一个包含top 和 left属性的对象,用整数指明元素横竖坐标
.offset( function(index, coords)) 添加于version 1.4
返回用于设置坐标的一个函数。接收匹配集中元素的索引作为第一个参数,当前坐标作为第二个参数。这个函数应该返回一个包含新 top 和
left 属性的对象。
.offset()设置方法允许我们重新定位一个元素,这个元素的位置是相对于文档。如果元素原先的
position属性值是
static的话,会被改写为
relative来实现重定位。
例子:
设置第二个的段落的偏移位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left:10px;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hellow</p><p>2nd Paragraph</p>
<script>
$("p:last").offset({ top: 10, left: 30 });
</script>
</body>
</html>
参考:http://www.css88.com/jqapi-1.9/offset/