How to get height of entire document with JavaScript?

前端 未结 13 1769
逝去的感伤
逝去的感伤 2020-11-22 06:01

Some documents I can\'t get the height of the document (to position something absolutely at the very bottom). Additionally, a padding-bottom on seems to do nothing on these

相关标签:
13条回答
  • 2020-11-22 06:32

    The proper answer for 2017 is:

    document.documentElement.getBoundingClientRect().height

    Unlike document.body.scrollHeight this method accounts for body margins. It also gives fractional height value, which can be useful in some cases

    0 讨论(0)
  • 2020-11-22 06:32

    To get the width in a cross browser/device way use:

    function getActualWidth() {
        var actualWidth = window.innerWidth ||
                          document.documentElement.clientWidth ||
                          document.body.clientWidth ||
                          document.body.offsetWidth;
    
        return actualWidth;
    }
    
    0 讨论(0)
  • 2020-11-22 06:37

    use blow code for compute height + scroll

    var dif = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    
    var height = dif + document.documentElement.scrollHeight +"px";
    
    0 讨论(0)
  • 2020-11-22 06:38

    I don't know about determining height just now, but you can use this to put something on the bottom:

    <html>
    <head>
    <title>CSS bottom test</title>
    <style>
    .bottom {
      position: absolute;
      bottom: 1em;
      left: 1em;
    }
    </style>
    </head>
    
    <body>
    
    <p>regular body stuff.</p>
    
    <div class='bottom'>on the bottom</div>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 06:42

    The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .

    If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.

    The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.

    Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.

    0 讨论(0)
  • 2020-11-22 06:45

    This is a really old question, and thus, has many outdated answers. As of 2020 all major browsers have adhered to the standard.

    Answer for 2020:

    document.body.scrollHeight
    

    Edit: the above doesn't take margins on the <body> tag into account. If your body has margins, use:

    document.documentElement.scrollHeight
    
    0 讨论(0)
提交回复
热议问题