HTMLElement: offsetLeft 屬性
HTMLElement 介面的只讀屬性 offsetLeft 返回當前元素左上角相對於 HTMLElement.offsetParent 節點的左側偏移畫素數。
對於塊級元素,offsetTop、offsetLeft、offsetWidth 和 offsetHeight 描述了元素相對於 offsetParent 的邊框盒。
然而,對於可以從一行換到另一行的內聯元素(例如 <span>),offsetTop 和 offsetLeft 描述的是第一個邊框盒的位置(使用 Element.getClientRects() 獲取其寬度和高度),而 offsetWidth 和 offsetHeight 描述的是邊界邊框盒的尺寸(使用 Element.getBoundingClientRect() 獲取其位置)。因此,具有 offsetLeft、offsetTop、offsetWidth 和 offsetHeight 的左、上、寬、高邊框盒將不是一個帶有換行文字的 span 的邊界盒。
值
一個整數。
示例
js
const colorTable = document.getElementById("t1");
const tOLeft = colorTable.offsetLeft;
if (tOLeft > 5) {
// large left offset: do something here
}
此示例顯示了一個“長”句子,它在一個帶有藍色邊框的 div 內換行,還有一個紅色框,您可能認為它應該描述 span 的邊界。

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 |
瀏覽器相容性
載入中…