获取窗口高度到小数点



我想获得我的窗口的高度。因此,我使用window.innerHeight

然而,这返回一个整数,我想要一个精确的值(float)。我想使用document.body.getBoundingClientRect().height,但这意味着添加一些css来填充整个窗口。如:

html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}

我怎样才能得到窗口的高度到小数点?

您可以通过编程将documentElementbody的高度设置为100%,获取高度,然后删除内联样式,以免进行任何持久的更改:

function getPreciseHeight() {
document.documentElement.style.height = "100%";
document.body.style.height = "100%";
const height = document.body.getBoundingClientRect().height;
document.documentElement.style.removeProperty('height');
document.body.style.removeProperty('height');
return height;
}
console.log("Normal:", document.body.getBoundingClientRect().height)

console.log("Fixed:", getPreciseHeight())
Hello World!