没有真正的官方 JavaScript 文档,但让我们看一下:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight
关于 HTMLElement.offsetHeight 他们说:
通常,元素的 offsetHeight 是以像素为单位的元素 CSS 高度的度量,包括边框、填充和元素的水平滚动条(如果存在,如果呈现)。
我知道 offsetHeight 的值在不同的浏览器中可能会有所不同,但这不是我的意思。我的观点是:
如果呈现
我做了一些测试,但我认为这是错误的和不正确的。在我看来,它必须是:“如果解析”而不是“如果呈现”。在互联网上,我看到很多人混淆了这些术语,而我认为它们是两个不同的东西。
渲染 = 在浏览器
解析中显示内容 = 构建 DOM 树
看这个测试:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<div id="result"></div>
<div id="container">
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
One line of html code<br />
</div>
<script>
// What is the offsetHeight of the html element "container" at this point?
var elmContainer = document.getElementById( 'container' );
var elmResult = document.getElementById( 'result' );
elmResult.innerHTML = 'Container offsetHeight is ' + elmContainer.offsetHeight + ' px';
// Synchronous delay of 5 seconds
var timeWhile = new Date().getTime();
while( new Date().getTime() - timeWhile < 5000 );
</script>
</body>
</html>
5 秒后在 Chrome 中显示:
Container offsetHeight is 180 px
后跟 html 代码行
5秒后在firefox中:
Container offsetHeight is 200 px
后跟html代码行
文档说它只会测量如果渲染的高度。但是当开始执行 5 秒的 javascript 延迟时,浏览器还没有在屏幕上显示任何内容。所以 HTMLElement 还没有被渲染!解析相同的 html 已经完成,因为“解析 html”和“执行 javascript”具有同步行为。
因此,如果我不得不相信文档,我希望 offsetHeight 为空或为零。我犯了一些错误还是文档确实不正确?
ps可能是“如果存在,如果渲染”仅指水平滚动条,但我做了一些其他测试,如果有滚动条,它将在浏览器在屏幕上显示任何内容之前(渲染之前)进行计算。因此,在这种情况下,我们将有与上述相同的故事。
ps 也许它看起来像一个不重要的细节,但我在互联网上的任何地方都可以使用 offsetHeight 来测量屏幕上显示的元素的高度。所以我想我可以用它来跟踪浏览器的渲染过程。但是当元素仍在渲染时,offsetHeight 的值已经是我完成渲染后的值。