HTMLElement: offsetLeft 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

HTMLElement 介面的只讀屬性 offsetLeft 返回當前元素左上角相對於 HTMLElement.offsetParent 節點的左側偏移畫素數。

對於塊級元素,offsetTopoffsetLeftoffsetWidthoffsetHeight 描述了元素相對於 offsetParent 的邊框盒。

然而,對於可以從一行換到另一行的內聯元素(例如 <span>),offsetTopoffsetLeft 描述的是第一個邊框盒的位置(使用 Element.getClientRects() 獲取其寬度和高度),而 offsetWidthoffsetHeight 描述的是邊界邊框盒的尺寸(使用 Element.getBoundingClientRect() 獲取其位置)。因此,具有 offsetLeftoffsetTopoffsetWidthoffsetHeight 的左、上、寬、高邊框盒將不是一個帶有換行文字的 span 的邊界盒。

一個整數。

示例

js
const colorTable = document.getElementById("t1");
const tOLeft = colorTable.offsetLeft;

if (tOLeft > 5) {
  // large left offset: do something here
}

此示例顯示了一個“長”句子,它在一個帶有藍色邊框的 div 內換行,還有一個紅色框,您可能認為它應該描述 span 的邊界。

A sentence that reads: Short span. This text is completely within a div with a blue border. A sentence that reads: Long span that wraps within this div. The words "long span that wraps" is within a box with a red border. The words "within this div" are within the div with the blue border.

html
<div class="span-container">
  <span>Short span.</span>
  <span id="long-span">Long span that wraps within this div.</span>
</div>

<div id="box"></div>
css
.span-container {
  width: 300px;
  border-color: blue;
  border-style: solid;
  border-width: 1px;
}

#box {
  position: absolute;
  border-color: red;
  border-width: 1px;
  border-style: solid;
  z-index: 10;
}
js
const box = document.getElementById("box");
const longSpan = document.getElementById("long-span");
box.style.left = `${longSpan.offsetLeft}${document.body.scrollLeft}px`;
box.style.top = `${longSpan.offsetTop}${document.body.scrollTop}px`;
box.style.width = `${longSpan.offsetWidth}px`;
box.style.height = `${longSpan.offsetHeight}px`;

規範

規範
CSSOM 檢視模組
# dom-htmlelement-offsetleft

瀏覽器相容性

另見