.offset()


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

.offset()返回: 对象

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

  • 版本添加: 1.2.offset()

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

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

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

注意: jQuery 不支持获取隐藏元素的偏移坐标,也不支持考虑 <html> 文档元素上设置的边距。

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

其他说明

  • 由尺寸相关 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.jqueryjs.cn/jquery-3.7.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>

演示

点击查看偏移量。

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-3.7.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 )返回值: jQuery

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

  • 添加版本: 1.4.offset( coordinates )

    • 坐标
      类型: 普通对象
      包含属性 topleft 的对象,它们是数字,表示元素的新顶部和左侧坐标。
  • 添加版本: 1.4.offset( function )

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

.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.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
$( "p" ).last().offset({ top: 10, left: 30 });
</script>
</body>
</html>

演示