JS 函数返回的 div 高度不正确。为什么?

sph*_*nks 8 javascript

我尝试获取页面上主 div 的大小,以使 iframe 将其高度更改为内容,但document.getElementById("divId").offsetHeight(也尝试innerHeight)返回错误的值。它总是返回 247,但实际上页面看起来减少了 75%。我知道页面没有完全加载,所以我将调整大小代码放在页面的页脚中,但它仍然返回 247。

$(document).ready(function() {
     console.log(document.getElementById("resizeDiv").offsetHeight);
});
Run Code Online (Sandbox Code Playgroud)

有什么建议么?

小智 7

添加 setTimeout 以等待屏幕加载并获取正确的高度。

setTimeout(() => {
    document.getElementById("resizeDiv").offsetHeight
}, 300);
Run Code Online (Sandbox Code Playgroud)


sph*_*nks 3

我找到了其他决定,我只得到身体的高度,效果很好:

var height = Math.max(
    document.body.scrollHeight, 
document.body.clientHeight, 
document.body.offsetHeight, 
document.documentElement.scrollHeight, 
document.documentElement.offsetHeight, 
document.documentElement.clientHeight);
Run Code Online (Sandbox Code Playgroud)