HTMLElement: thuộc tính offsetLeft
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Thuộc tính chỉ đọc offsetLeft của giao diện HTMLElement trả về số pixel mà góc trên bên trái của phần tử hiện tại bị lệch sang trái trong nút HTMLElement.offsetParent.
Đối với các phần tử cấp khối, offsetTop, offsetLeft, offsetWidth và offsetHeight mô tả hộp viền của một phần tử tương đối với offsetParent.
Tuy nhiên, đối với các phần tử cấp nội tuyến (như <span>) có thể bao sang dòng tiếp theo, offsetTop và offsetLeft mô tả vị trí của hộp viền đầu tiên (dùng Element.getClientRects() để lấy chiều rộng và chiều cao của nó), trong khi offsetWidth và offsetHeight mô tả kích thước của hộp viền bao quanh (dùng Element.getBoundingClientRect() để lấy vị trí của nó). Do đó, hộp có left, top, width và height là offsetLeft, offsetTop, offsetWidth và offsetHeight sẽ không phải là hộp bao quanh cho span có văn bản bao dòng.
Giá trị
Một số nguyên.
Ví dụ
const colorTable = document.getElementById("t1");
const tOLeft = colorTable.offsetLeft;
if (tOLeft > 5) {
// large left offset: do something here
}
Ví dụ này cho thấy một câu 'dài' bao trong div có viền xanh, và một hộp đỏ mà người ta có thể nghĩ sẽ mô tả ranh giới của span.

<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`;
Thông số kỹ thuật
| Specification |
|---|
| CSSOM View Module> # dom-htmlelement-offsetleft> |