为什么 clientHeight 不是 150px?

why isn't clientHeight 150px?

let height = document.getElementById('d').clientHeight
console.log(height);
img{
height:100%;}
<div id = 'd'>
<img src="https://via.placeholder.com/100x150">
</div>

因为您的代码执行时图片还没有加载:

setTimeout(() => {
    let height = document.getElementById('d').clientHeight
    console.log(height);
}, 1000)
<div id = 'd'>
<img src="https://via.placeholder.com/100x150">
</div>

如果您的代码依赖于知道图像的高度才能正确 运行,您需要 check whether the image is loaded, and wait until it has if it hasn't yet

当您在控制台记录时图像没有加载。您可以创建一个等待图像加载的事件侦听器,然后它会显示正确的高度。

function loaded() {
    let height = document.getElementById('d').clientHeight;
    console.log(height);
}

const img = document.getElementById('img');
if (img.complete) {
  loaded()
} else {
  img.addEventListener('load', loaded)
}
img{
height:100%;}
<div id = 'd'>
<img id='img' src="https://via.placeholder.com/100x150">
</div>

load 事件在整个页面加载完成后触发,包括样式表和图像等所有相关资源。这与 DOMContentLoaded 形成对比,后者在页面 DOM 加载后立即触发,无需等待资源完成加载。

addEventListener('load',(event)=>{
    let height = document.getElementById('d').clientHeight
    console.log(height);
});