某些網站(如stackoverflow.com這裏)設置了<html>
和/或<body>
元素的height: 100%
和/或width: 100%
(出於某種原因,我不明白)。對於文檔中的所有元素(afaik),CSS默認設置爲overflow: visible
,所以與其父元素邊界重疊的子元素不會被截斷,如果它們離開視口,瀏覽器可能會顯示滾動條。到現在爲止還挺好。使用JavaScript獲取文檔的真實大小
但如果height: 100%
爲兩個元素集,html
和body
,如何找出整個文檔的實際(全)的大小呢?在這種情況下,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」,是因爲計算器。 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的文件的完整大小?
使用'clientHeight',我再次獲得相同的視口尺寸。但'scrollHeight'看起來不錯。我認爲這可能是解決方案。我必須先測試它,但我感謝你的提示!測試後我會回覆你。 – StanE