`offsetLeft`和' clientLeft'之间有什么区别?在javascript中

时间:2014-11-29 05:36:50

标签: javascript html

我在此网站以及clientLeftOffsetLeft上的其他网站上阅读了很多答案。但是没有一个人能够全面解释这些价值观是什么。

此外,网上有几个消息来源提供令人困惑或不正确的信息。

有人可以通过视觉示例给出正确的解释吗?
如何在不使用任何CSS的情况下更改这些值。我的意思是只使用JavaScript。

2 个答案:

答案 0 :(得分:13)

来自第一个定位的父级 left edge

offsetLeft =位置left + margin
clientLeft = 左边框 + 左滚动条宽度(如果存在)。 (block级元素 - 通常!)


我们假设我们有<div> 8px边框和滚动条

&#13;
&#13;
var el = document.getElementById("test");
console.log( el.offsetLeft );  // (left + margin)           80 + 10 = 90
console.log( el.clientLeft );  // (border + left scrollbar)  8 +  0 = 8
&#13;
#test {
  overflow: auto;
  position: absolute;
  
  left:         80px; /* + */
  margin-left:  10px; /* = 90px offsetLeft */
  
  height:  100px;
  width:   100px;
  
  border: 8px solid red;
  background: #f8f8f8;
}
&#13;
<div id="test">
  a<br>a<br>a<br>a<br>a<br>a<br>a<br>a
</div>
&#13;
&#13;
&#13;


有趣的部分

使用从右到左 文字方向 direction: rtl;
返回的值为: border + left scrollBar width(通常为17px)。

  

8px border + 17px scrollbar * = ~25px

*(取决于浏览器默认或自定义样式)

&#13;
&#13;
var el = document.getElementById("test");
console.log( el.offsetLeft );  // (left + margin)            80 +  10 = 90
console.log( el.clientLeft );  // (border + left scrollbar*)  8 + ~17 = 25
&#13;
#test {
  overflow: auto;
  position: absolute;
  
  left:         80px; /* + */
  margin-left:  10px; /* = 90px offsetLeft */
  
  height:  100px;
  width:   100px;
  
  border: 8px solid red;
  background: #f8f8f8;

  direction: rtl;   /* now text is `rtl` and scrollbar is at the left side! */

}
&#13;
<div id="test">
  a<br>a<br>a<br>a<br>a<br>a<br>a<br>a
</div>
&#13;
&#13;
&#13;

<子> 资源:
http://msdn.microsoft.com/en-us/library/ie/ms533564%28v=vs.85%29.aspx
https://developer.mozilla.org/en-US/docs/Web/API/Element.clientLeft
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetLeft

答案 1 :(得分:11)

上面的答案很好地解释了,但这是一张从this wonderful tutorial on coordinates开始的精彩照片。 offsetLeft vs clientLeft