总有人间一两风,填我十万八千梦

jQuery .offset() 用法 手册 | 示例代码

jQuery开发手册 归档 334℃ 0评论

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

  • 添加的版本: 1.2.offset()

    • 这个方法不接受任何参数

.offset()方法允许我们检索一个元素相对于文档(document)的当前位置。和.position()的差别在于:.position()是相对于相对于父级元素的位移。当通过全局操作(特别是通过拖拽操作)将一个新的元素放置到另一个已经存在的元素的上面时,若要取得这个新的元素的位置,那么使用 .offset() 更合适。

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

注意:jQuery不支持获取隐藏元素的偏移坐标。同样的,也无法取得隐藏元素的 border, margin, 或 padding 信息。

若元素的属性设置的是 visibility:hidden,那么我们依然可以取得它的坐标。但是若设置的属性是 display:none,由于在绘制 DOM 树时根本就不绘制该元素,所以它的位置属性值是 undefined。

例子:

Example: 使用第二个段落的位置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<style>
p { margin-left:10px; }
</style>
<script src="https://code.jquery.com/jquery-latest.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>

Example: 点击查看位置。

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
<!DOCTYPE html>
<html>
<head>
<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-latest.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 (e) {
var offset = $(this).offset();
e.stopPropagation();
$("#result").text(this.tagName + " coords ( " + offset.left + ", " +
offset.top + " )");
});
</script>
</body>
</html>

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

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

    • coordinates
      类型: PlainObject
      一个包含topleft属性的对象,用整数指明元素的新顶部和左边坐标。
  • 添加的版本: 1.4.offset( function(index, coords) )

    • function(index, coords)
      类型: Function()
      返回用于设置坐标的一个函数。接收元素在匹配的元素集合中的索引位置作为第一个参数,和当前坐标作为第二个参数。这个函数应该返回一个包含topleft属性的对象。

.offset()方法允许我们重新设置元素的位置,这个元素的位置是相对于document对象的。如果对象原先的position样式属性是static的话,会被改成relative来实现重定位。

例子:

设置第二个段落的位置:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<style>p { margin-left:10px; } </style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>$("p:last").offset({ top: 10, left: 30 });</script>
</body>
</html>

转载请注明:悠然品鉴 » jQuery .offset() 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址