How to get height of entire document with JavaScript?

前端 未结 13 1779
逝去的感伤
逝去的感伤 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:26

    For anyone having trouble scrolling a page on demand, using feature detection, I've come up with this hack to detect which feature to use in an animated scroll.

    The issue was both document.body.scrollTop and document.documentElement always returned true in all browsers.

    However you can only actually scroll a document with either one or the other. d.body.scrollTop for Safari and document.documentElement for all others according to w3schools (see examples)

    element.scrollTop works in all browsers, not so for document level.

        // get and test orig scroll pos in Saf and similar 
        var ORG = d.body.scrollTop; 
    
        // increment by 1 pixel
        d.body.scrollTop += 1;
    
        // get new scroll pos in Saf and similar 
        var NEW = d.body.scrollTop;
    
        if(ORG == NEW){
            // no change, try scroll up instead
            ORG = d.body.scrollTop;
            d.body.scrollTop -= 1;
            NEW = d.body.scrollTop;
    
            if(ORG == NEW){
                // still no change, use document.documentElement
                cont = dd;
            } else {
                // we measured movement, use document.body
                cont = d.body;
            }
        } else {
            // we measured movement, use document.body
            cont = d.body;
        }
    

提交回复
热议问题