HTMLElement: offsetLeft property
MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونهکد
{{ APIRef("HTML DOM") }}
The **offsetLeft** read-only property of the {{domxref("HTMLElement")}} interface returns the number of pixels that the _upper left corner_ of the current element is offset to the left within the {{domxref("HTMLElement.offsetParent")}} node.
For block-level elements, offsetTop, offsetLeft, offsetWidth, and offsetHeight describe the border box of an element relative to the offsetParent.
However, for inline-level elements (such as <span>) that can wrap from one line to the next, offsetTop and offsetLeft describe the positions of the _first_ border box (use {{domxref("Element.getClientRects()")}} to get its width and height), while offsetWidth and offsetHeight describe the dimensions of the _bounding_ border box (use {{domxref("Element.getBoundingClientRect()")}} to get its position). Therefore, a box with the left, top, width and height of offsetLeft, offsetTop, offsetWidth and offsetHeight will not be a bounding box for a span with wrapped text.
Value
An integer.
Examples
const colorTable = document.getElementById("t1");
const tOLeft = colorTable.offsetLeft;
if (tOLeft > 5) {
// large left offset: do something here
}This example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the 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.
<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>.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;
}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`;Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- Determining the dimensions of elements
- {{domxref("Element.clientLeft")}}
- {{domxref("Element.scrollLeft")}}
- {{domxref("HTMLElement.offsetHeight")}}
- {{domxref("HTMLElement.offsetWidth")}}
- {{domxref("HTMLElement.offsetTop")}}
- {{domxref("Element.getBoundingClientRect()")}}