gpt4 book ai didi

javascript - 使用 JavaScript 获取文档的真实大小

转载 作者:行者123 更新时间:2023-11-28 15:16:49 24 4
gpt4 key购买 nike

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

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

尝试一下:转到 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 转换,比如倾斜)。我能想到的唯一方法是遍历文档中的 all 元素,获取它们底部边缘的绝对(相对于文档边界)位置并取最高值。也许是这样的:

(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 找出文档的完整大小?

最佳答案

查看这篇关于视口(viewport)、设备和文档大小的文章 https://www.kirupa.com/html5/viewport_device_document_size.htm.In为了获得真实的文档大小,它是使用 document.body.clientWidth 和 document.body.clientHeight。我试过 https://stackoverflow.com/我得到的结果与 8416 相同,对吗?

关于javascript - 使用 JavaScript 获取文档的真实大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46995350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com