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 |
浏览器兼容性
加载中…