我在这个网站以及 clientLeft 和 OffsetLeft 的其他网站上阅读了很多答案 . 但没有一个人能够全面解释这些 Value 观 .
clientLeft
OffsetLeft
此外,网上有几个来源,提供令人困惑或不正确的信息 .
有人可以通过视觉示例给我正确解释这些术语吗?如何在不使用任何CSS的情况下更改这些值 . 我的意思是只使用JavaScript .
offsetLeft =位置 left margin 来自第一个定位的父级left edge .clientLeft = left border left scrollbar width (如果有的话) . ( block 级元素 - 只!)
offsetLeft
left
margin
block
假设我们有一个带有8px边框和滚动条的 <div>
<div>
var el = document.getElementById("test"); console.log( el.offsetLeft ); // (left + margin) 80 + 10 = 90 console.log( el.clientLeft ); // (border + left scrollbar) 8 + 0 = 8
#test { overflow: auto; position: absolute; left: 80px; /* + */ margin-left: 10px; /* = 90px offsetLeft */ height: 100px; width: 100px; border: 8px solid red; background: #f8f8f8; }
<div id="test"> a<br>a<br>a<br>a<br>a<br>a<br>a<br>a </div>
使用 Right-To-Left 文字方向 direction: rtl;返回的值将是: border + left scrollBar width(通常为17px) .
direction: rtl;
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
#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! */ }
资源: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
上面的答案解释得很好,但这是一张很好的照片,形式是this wonderful tutorial on coordinates .
2 回答
offsetLeft
=位置left
margin
来自第一个定位的父级left edge .clientLeft
= left border left scrollbar width (如果有的话) . (block
级元素 - 只!)假设我们有一个带有8px边框和滚动条的
<div>
有趣的部分
使用 Right-To-Left 文字方向
direction: rtl;
返回的值将是: border + left scrollBar width(通常为17px) .
*(取决于浏览器默认或自定义样式)
资源: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
上面的答案解释得很好,但这是一张很好的照片,形式是this wonderful tutorial on coordinates .