what is the difference between `offsetLeft` and 'clientLeft' in javascript
我在本网站以及
另外,网络上有多个来源提供令人困惑或不正确的信息。
有人可以通过一个直观的例子给我这些术语的正确解释吗?
以及如何在不使用任何CSS的情况下更改这些值。 我的意思是只使用JavaScript。
上面的答案很好地说明了这一点,但这是这张精彩的坐标教程所拍摄的精美照片。
边缘。
假设我们有一个
1 2 3 | var el = document.getElementById("test"); console.log( el.offsetLeft ); // (left + margin) 80 + 10 = 90 console.log( el.clientLeft ); // (border + left scrollbar) 8 + 0 = 8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | #test { overflow: auto; position: absolute; left: 80px; /* + */ margin-left: 10px; /* = 90px offsetLeft */ height: 100px; width: 100px; border: 8px solid red; background: #f8f8f8; } |
1 | aaaaaaaa |
有趣的部分
使用从右到左的文本方向
返回的值将是:border + left scrollBar width(通常为17px)。
8px border + 17px scrollbar* = ~25px
*(取决于浏览器的默认样式或自定义样式)
1 2 3 | var el = document.getElementById("test"); console.log( el.offsetLeft ); // (left + margin) 80 + 10 = 90 console.log( el.clientLeft ); // (border + left scrollbar*) 8 + ~17 = 25 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #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! */ } |
1 | aaaaaaaa |
资源:
http://msdn.microsoft.com/zh-cn/library/ie/ms533564%28v=vs.85%29.aspx
https://developer.mozilla.org/zh-CN/docs/Web/API/Element.clientLeft
https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement.offsetLeft
sub>