difference between offsetHeight and clientHeight

前端 未结 2 812
梦毁少年i
梦毁少年i 2020-11-27 09:35

In the javascript dom - what is the difference between offsetHeight and clientHeight of an element?

相关标签:
2条回答
  • 2020-11-27 10:13

    The answer from Oded is the theory. But the theory and the reality are not always the same, at least not for the <BODY> or the <HTML> elements which may be important for scrolling operations in javascript.

    Microsoft has a nice image in the MSDN:

    ClientHeight, OffsetHeight, ScrollHeight

    If you have a HTML page which shows a vertical scrollbar one would expect that either the <BODY> or the <HTML> element has a ScrollHeight geater than OffsetHeight as this image shows. This is true for all older versions of Internet Explorer.

    But it is not true for Internet Explorer 11 and not for Firefox 36. At least in these browsers OffsetHeight is nearly the same as ScrollHeight which is wrong.

    And while OffsetHeight may be wrong, ClientHeight is always correct.

    Try the following code on different browsers and you will see:

    <!DOCTYPE html>
    <html>
    <body>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <script>
        document.write("Body off: " + document.body.offsetHeight 
                 + "<br>Body cli: " + document.body.clientHeight
                 + "<br>Html off: " + document.body.parentElement.offsetHeight               
                 + "<br>Html cli: " + document.body.parentElement.clientHeight);
    </script>
    </body>
    </html>
    

    While older Internet Explorer shows correctly:

    Body off: 1197
    Body cli: 1197
    Html off: 878
    Html cli: 874  
    

    The output from Firefox and Internet Explorer 11 is:

    Body off: 1260
    Body cli: 1260
    Html off: 1276   // this is completely wrong
    Html cli: 889
    

    which shows clearly that offsetHeight is wrong here. OffsetHeight and ClientHeight should differ only a few pixels or be the same.


    Please note that ClientHeight and OffsetHeight may also differ extremely for elements that are not visible like for example a <FORM> where OffsetHeight may be the real size of the FORM while ClientHeight may be zero.

    0 讨论(0)
  • 2020-11-27 10:19

    clientHeight:

    Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, but it does not include the scrollBar, border, and the margin.

    offsetHeight:

    Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, scrollBar, and the border, but does not include the margin.

    So, offsetHeight includes scrollbar and border, clientHeight doesn't.

    0 讨论(0)
提交回复
热议问题