【问题标题】:what is the difference between `offsetLeft` and 'clientLeft' in javascriptjavascript中的`offsetLeft`和'clientLeft'有什么区别
【发布时间】:2015-01-27 17:42:48
【问题描述】:

我在这个网站和clientLeftOffsetLeft 上的其他网站上阅读了许多答案。但没有人全面解释这些值是什么。

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

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

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    offsetLeft = 位置left+margin 来自第一个定位的父级 left edge
    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
    #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>


    有趣的部分

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

    8px 边框 + 17px 滚动条* = ~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! */
    
    }
    <div id="test">
      a<br>a<br>a<br>a<br>a<br>a<br>a<br>a
    </div>

    资源:
    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

    【讨论】:

      【解决方案2】:

      上面的答案很好地解释了它,但这是一张从this wonderful tutorial on coordinates 拍摄的漂亮照片。

      【讨论】:

        猜你喜欢
        • 2011-11-10
        • 1970-01-01
        • 2011-06-28
        • 1970-01-01
        • 2010-09-19
        • 2010-10-29
        • 2010-09-13
        • 1970-01-01
        相关资源
        最近更新 更多