我在此网站以及clientLeft
和OffsetLeft
上的其他网站上阅读了很多答案。但是没有一个人能够全面解释这些价值观是什么。
此外,网上有几个消息来源提供令人困惑或不正确的信息。
有人可以通过视觉示例给出正确的解释吗?
如何在不使用任何CSS的情况下更改这些值。我的意思是只使用JavaScript。
答案 0 :(得分:13)
offsetLeft
=位置left
+ margin
。
clientLeft
= 左边框 + 左滚动条宽度(如果存在)。 (block
级元素 - 通常!)
我们假设我们有<div>
8px边框和滚动条
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;
使用从右到左 文字方向 direction: rtl;
返回的值为: border + left scrollBar width(通常为17px)。
8px border + 17px scrollbar * = ~25px
*(取决于浏览器默认或自定义样式)
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;
<子>
资源:
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开始的精彩照片。