.offset()
返回: Object
.offset()
描述:获得匹配的元素集合中的第一个元素的相对于document的当前坐标。
加入于: 1.2
.offset()该方法不接受任何参数
.offset()方法允许我们检索一个元素相对于document的当前位置。相较之下,.position()是检索元素相对于最接近的有定位的祖先元素的位置。当通过全局操作(特别是通过拖拽操作)将一个新的元素放置到另一个已经存在的元素的上面时,若要取得这个新的元素的位置,那么.offset()会很有用。
.offset()返回一个包含top和left属性的对象 。
注意:jQuery不支持获得隐藏元素的坐标,同样的,也无法取得隐藏元素的 border, margin, 或 padding 信息。
虽然它能够获得带visibility:hidden设置的元素的坐标,但是因为带有display:none设置的元素不包含在呈现树内,所以它的位置也是未知的。
其它说明
- 维度相关的API返回的数字,包括
.offset(),在一些情况中可能是分数。代码不应该假定它是一个整数。当用户缩放网页的时候,维度可能不正确;浏览器没有提供侦测这种情况的API。
示例
访问第二个段落文本的偏移:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left: 10px;
}
</style>
<script src="https://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 {
width: 50px;
height: 50px;
position: absolute;
left: 220px;
top: 35px;
background-color: green;
cursor: pointer;
}
</style>
<script src="https://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>
演示结果
返回: jQuery
.offset()
描述:或者对匹配的元素集合中的每个元素设置相对于document的坐标。
加入于: 1.4
.offset( coordinates )- coordinates类型:PlainObject一个对象,它包含了属性
top和属性left,它们是针对每个元素表示新的top和left坐标的数字。
加入于: 1.4
.offset( function )- function一个函数,它返回要设置的坐标。接受元素在集合中的索引作为第一个参数,当前的坐标作为第二个参数。该函数必须返回一个对象,带有属性
top和属性left。
.offset()设置器方法允许我们重定位一个元素。元素的位置被指定为相对于document。如果元素的CSS样式属性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="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
$( "p:last" ).offset({ top: 10, left: 30 });
</script>
</body>
</html>
演示结果