.offset()

在匹配的元素集合中,相对于文档,取得第一个元素的当前坐标,或者设置每个元素的坐标。

.offset()返回类型:Object

描述:取得匹配的元素集合中第一个元素的当前坐标,相对于文档。

  • 增补版本:1.2.offset()

    • 此方法不接受任何参数。

.offset()方法允许我们检索元素的相对于文档的当前位置(特别是它的边框盒,它排除了边距)。相较之下,.position()是检索相对于定位父元素的当前位置。在通过全局操作(特别是通过拖拽操作)将一个新的元素放置到另一个已经存在的元素的上面时,若要取得这个新的元素的位置,那么使用 .offset()更合适。

.offset()返回一个对象,包含了属性topleft

注意:jQuery并不支持取得隐藏元素的偏移坐标或计算<html>文档元素上的边距设置。

它可以取得带有visibility:hidden设置的元素的坐标,但是display:none被排除在呈现树之外,所以位置就是undefined。

补充说明:

  • 由尺寸相关的API返回的数字,包括.offset(),在一些情况下有可能是小数。代码并不假设它是一个整型数。而且,当用户缩放网页时,尺寸可能不正确;浏览器并不曝露一个API,以诊测此条件。

示例:

访问第二个段落的偏移:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!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>

演示:

点击以查看偏移。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!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>

演示:

.offset( coordinates )返回类型:jQuery

描述:设置匹配的元素集合中每个元素的当前坐标,相对于文档。

  • 增补版本:1.4.offset( coordinates )

    • coordinates
      类型:PlainObject
      一个对象,包含了属性topleft,它们是数字,指示针对元素的新top和left坐标。
  • 增补版本:1.4.offset( function )

    • function
      类型:Function( Integer index, PlainObject coords ) => PlainObject
      一个函数,返回要设置的坐标。接受集合中元素的索引作为第一个参数,当前的坐标作为第二个参数。此函数应该返回一个对象,带有新的top属性和left属性。

.offset()设置器方法允许我们重定位一个元素。相对于文档指定元素的边框盒位置。如果元素的position样式属性目前是static,它会被设置为relative以允许这个重定位。

示例:

设置第二个段落的偏移:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!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>

演示: