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

浏览器兼容性

另见