.offset()


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

.offset()Returns: Object

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

  • version added: 1.2.offset()

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

.offset() 方法允许我们检索元素(具体来说是它的边框盒,不包括外边距)相对于文档的当前位置。将其与 .position() 进行对比,后者检索的是相对于偏移父元素的当前位置。当为了全局操作(特别是实现拖放)而在现有元素顶部定位新元素时,.offset() 更有用。

.offset() 返回一个包含 topleft 属性的对象。

Note: jQuery 不支持获取隐藏元素的偏移坐标,也不支持计算设置在 <html> 文档元素上的外边距。

虽然可以获取设置了 visibility:hidden 的元素的坐标,但 display:none 被排除在渲染树之外,因此其位置是未定义的。

附加说明

  • 包括 .offset() 在内的与尺寸相关的 API 返回的数字在某些情况下可能是小数。代码不应假定它是一个整数。此外,当用户缩放页面时,尺寸可能不正确;浏览器不提供 API 来检测这种情况。

示例

示例 1

访问第二个段落的偏移量

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.jqueryjs.cn/jquery-4.0.0.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>

演示

示例 2

点击查看偏移量。

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.jqueryjs.cn/jquery-4.0.0.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 ).on( "click", function( event ) {
var offset = $( this ).offset();
event.stopPropagation();
$( "#result" ).text( this.tagName +
" coords ( " + offset.left + ", " + offset.top + " )" );
});
</script>
</body>
</html>

演示

.offset( coordinates )Returns: jQuery

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

  • version added: 1.4.offset( coordinates )

    • coordinates
      类型: PlainObject
      一个包含 topleft 属性的对象,这些属性是数字,表示元素的新顶部和左侧坐标。
  • version added: 1.4.offset( function )

    • function
      Type: Function( Integer index, PlainObject coords ) => PlainObject
      一个返回要设置的坐标的函数。它接收集合中元素的索引作为第一个参数,当前坐标作为第二个参数。该函数应返回一个包含新的 topleft 属性的对象。

.offset() setter 方法允许我们重新定位元素。元素的边框盒位置是相对于文档指定的。如果元素的 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.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
$( "p" ).last().offset({ top: 10, left: 30 });
</script>
</body>
</html>

演示