首页 文章

javascript中`offsetLeft`和'clientLeft'之间的区别是什么?

提问于
浏览
10

我在这个网站以及 clientLeftOffsetLeft 的其他网站上阅读了很多答案 . 但没有一个人能够全面解释这些 Value 观 .

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

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

2 回答

  • 13

    offsetLeft =位置 left margin 来自第一个定位的父级left edge .
    clientLeft = left border left scrollbar width (如果有的话) . ( block 级元素 - 只!)


    假设我们有一个带有8px边框和滚动条的 <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) .

    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! */
    
    }
    
    <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

  • 10

    上面的答案解释得很好,但这是一张很好的照片,形式是this wonderful tutorial on coordinates .
    offsetLeft vs clientLeft

相关问题