繁体   English   中英

使用 JavaScript 获取文档的实际大小

[英]Getting real size of document with JavaScript

一些网站(比如这里的 stackoverflow.com)设置height: 100%和/或width: 100%<html>和/或<body>元素(出于某种原因,我不明白)。 CSS 默认设置overflow: visible对文档中的所有元素overflow: visible (afaik),因此与父元素边界重叠的子元素不会被切断,如果它们离开视口,浏览器可能会显示滚动条。 到现在为止还挺好。

但是如果height: 100%htmlbody两个元素都设置了,那么如何找出整个文档的真实(完整)大小呢? 在这种情况下document.documentElement.getBoundingClientRect()document.body.getBoundingClientRect()将只返回可见视口的高度。

试试看:转到https://stackoverflow.com/并在控制台中执行以下代码:

var de = document.documentElement;
var b = document.body;

console.log('Before:');
console.log(de.getBoundingClientRect().height);  // or de.offsetHeight
console.log(b.getBoundingClientRect().height);  // or b.offsetHeight

de.style.height = '100%';
b.style.height = '100%';

console.log('After:');
console.log(de.getBoundingClientRect().height);  // or de.offsetHeight
console.log(b.getBoundingClientRect().height);  // or b.offsetHeight

在我的情况下,输出是:

Before:
638
8352.2333984375
After:
638
638

第一个“638”是因为在 stackoverflow.com 上<html>元素的 CSS height属性已经设置为 100%,就像我上面写的那样。 但是垂直滚动条仍然可见,页面可以向下滚动。

那么如果两个元素的高度都设置为 100%,我还需要哪些其他选项才能找出整个文档的真实大小? offsetHeight返回相同的值,因此不能使用它(它也不会遵守任何 CSS 转换,例如倾斜)。 我能想到的唯一方法是遍历文档中的所有元素,获取它们底部边缘的绝对(相对于文档边界)位置并取最高值。 也许是这样的:

(function() {
    var getAbsolutePos = function(elm) {
        var pos = {x: 0, y: 0};

        if (elm.offsetParent) {
            do {
                pos.x += elm.offsetLeft;
                pos.y += elm.offsetTop;
            } while (elm = elm.offsetParent);
        }

        return pos;
    };

    var e = document.querySelectorAll("*");
    var btm, docHeight = 0;
    for (var i=0; i < e.length; ++i)
    {
        btm = getAbsolutePos(e[i]).y + e[i].offsetHeight;
        if (btm > docHeight) {
            docHeight = btm;
        }
    }

    console.log('Page height: ' + docHeight);
})();

// Output: "Page height: 8416"

但这看起来很脏,我猜这可能是资源密集型的(取决于元素数量),尤其是当这种计算发生在 onMouseMove 事件中时。 更糟糕的是在移动设备上,功耗会增加。

有没有其他更有效的方法来使用纯 JavaScript 找出文档的完整大小?

查看这篇关于视口、设备和文档大小的文章https://www.kirupa.com/html5/viewport_device_document_size.htm。为了获得真实的文档大小,使用 document.body.clientWidth 和 document.body。客户端高度。 https://stackoverflow.com/ 中尝试过,我得到的结果与 8416 相同,对吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM