.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.jquery.com/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.jquery.com/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 )

    • coordinates
      類型: PlainObject
      包含 topleft 屬性的物件,這些屬性是表示元素的新頂端和左側座標的數字。
  • 新增版本: 1.4.offset( function )

    • function
      類型: Function( Integer index, PlainObject coords ) => PlainObject
      傳回要設定的座標的函數。接收集合中元素的索引作為第一個引數,以及目前的座標作為第二個引數。函數應傳回一個物件,其中包含新的 topleft 屬性。

.offset() setter 方法讓我們重新定位元素。元素的 border-box 位置會指定為相對於文件。如果元素的 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-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>

示範