Get page height in JS (Cross-Browser)

后端 未结 3 1524
温柔的废话
温柔的废话 2021-02-15 15:34

What is the best way to get the actual page (not window) height in JS that is cross-browser compatible?

I\'ve seen a few ways but they all return different values...

3条回答
  •  别那么骄傲
    2021-02-15 16:35

    Page/Document height is currently subject to vendor (IE/Moz/Apple/...) implementation and does not have a standard and consistent result cross-browser.

    Looking at JQuery .height() method;

    if ( jQuery.isWindow( elem ) ) {
                // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
                // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
                var docElemProp = elem.document.documentElement[ "client" + name ],
                    body = elem.document.body;
                return elem.document.compatMode === "CSS1Compat" && docElemProp ||
                    body && body[ "client" + name ] || docElemProp;
    
            // Get document width or height
            } else if ( elem.nodeType === 9 ) {
                // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
                return Math.max(
                    elem.documentElement["client" + name],
                    elem.body["scroll" + name], elem.documentElement["scroll" + name],
                    elem.body["offset" + name], elem.documentElement["offset" + name]
                );
    

    nodeType === 9 mean DOCUMENT_NODE : http://www.javascriptkit.com/domref/nodetype.shtml so no JQuery code solution should looks like:

    var height = Math.max(
                        elem.documentElement.clientHeight,
                        elem.body.scrollHeight, elem.documentElement.scrollHeight,
                        elem.body.offsetHeight, elem.documentElement.offsetHeight)
    

提交回复
热议问题