在JS中获取页面高度

在JS中获取页面高度

本文介绍了在JS中获取页面高度(跨浏览器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在跨浏览器兼容的JS中获取实际页面(非窗口)高度的最佳方法是什么?

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...

self.innerHeight

document.documentElement.clientHeight

document.body.clientHeight
或其他?

self.innerHeightordocument.documentElement.clientHeightordocument.body.clientHeightor something else?

这样做的一种方法似乎有效:

One way of doing it which seems to work is :

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight,
                       html.clientHeight, html.scrollHeight, html.offsetHeight );


推荐答案

页面/文档高度目前受制于供应商(IE / Moz / Apple / ...)实现并没有标准和一致的结果跨浏览器。

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

查看JQuery .height()方法;

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表示DOCUMENT_NODE:
所以没有JQuery代码解决方案应该是这样的:

nodeType === 9 mean DOCUMENT_NODE : http://www.javascriptkit.com/domref/nodetype.shtmlso 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)

这篇关于在JS中获取页面高度(跨浏览器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:51