HTMLElement.offsetLeft 是一个只读属性,返回当前元素左上角相对于 HTMLElement.offsetParent 节点的左边界偏移的像素值。
对块级元素来说,offsetTop、offsetLeft、offsetWidth 及 offsetHeight 描述了元素相对于 offsetParent 的边界框。
然而,对于可被截断到下一行的行内元素(如 span),offsetTop 和 offsetLeft 描述的是第一个边界框的位置(使用 Element.getClientRects() 来获取其宽度和高度),而 offsetWidth 和 offsetHeight 描述的是边界框的维度(使用 Element.getBoundingClientRect 来获取其位置)。因此,使用 offsetLeft、offsetTop、offsetWidth、offsetHeight 来对应 left、top、width 和 height 的一个盒子将不会是文本容器 span 的盒子边界。
语法
left = element.offsetLeft;
left 是一个整数,表示向左偏移的像素值。
示例
var colorTable = document.getElementById("t1");
var tOLeft = colorTable.offsetLeft;
if (tOLeft > 5) {
// large left offset: do something here
}
这个例子展示了蓝色边框的 div 包含一个长的句子,红色的盒子是一个可以表示包含这个长句子的span标签的边界。
<div style="width: 300px; border-color:blue;
border-style:solid; border-width:1;">
<span>Short span. </span>
<span id="long">Long span that wraps withing this div.</span>
</div>
<div id="box" style="position: absolute; border-color: red;
border-width: 1; border-style: solid; z-index: 10">
</div>
<script>
var box = document.getElementById("box");
var long = document.getElementById("long");
//
// long.offsetLeft这个值就是span的offsetLeft.
// span是个行内元素,它没有absolute定位,但还是默认offsetParent就是父元素,而不是根
//
box.style.left = long.offsetLeft + document.body.scrollLeft + "px";
box.style.top = long.offsetTop + document.body.scrollTop + "px";
box.style.width = long.offsetWidth + "px";
box.style.height = long.offsetHeight + "px";
</script>
规范
| Specification | Status | Comment |
|---|---|---|
| CSS Object Model (CSSOM) View Module offsetLeft |
Working Draft |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | (Yes) | ? | ? | ? | ? |
| Feature | Android | Android Webview | Firefox Mobile (Gecko) | Firefox OS | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|---|
| Basic support | ? | (Yes) | ? | ? | ? | ? | ? | (Yes) |
根据规范,如果元素被隐藏(此元素的 style.display 或任何祖先为“none”),或者如果元素本身的 style.position 设置为“fixed”,则此属性将在Webkit上返回null 。
在 Internet Explorer (9) 上如果元素的 style.position 是 "fixed",则该属性为 null (样式 display:none 不会影响。)