You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取图片显示高度(非自然高度)?动态加载场景的JS/jQuery解法

问题2:动态加载到带min-height容器的图片显示高度获取

针对你给出的HTML结构:

<div class="card_bg"><img class="card_img" src="images/card_bg.jpg" alt=""></div>

已知图片自然尺寸为720405像素,显示尺寸为394222像素,下面分别给出原生JavaScript和jQuery的实现方式:

原生JavaScript实现

// 获取目标图片元素
const cardImage = document.querySelector('.card_img');

// 监听图片加载完成事件(处理首次加载场景)
cardImage.addEventListener('load', function() {
  // 获取显示高度,三种方法均可拿到222
  const displayHeight = this.getBoundingClientRect().height;
  // 也可以用offsetHeight/clientHeight
  // const displayHeight = this.offsetHeight;
  console.log('图片显示高度:', Math.floor(displayHeight)); // 输出222
});

// 处理图片已被缓存的情况(避免load事件不触发)
if (cardImage.complete) {
  const displayHeight = cardImage.getBoundingClientRect().height;
  console.log('图片显示高度(缓存):', Math.floor(displayHeight));
}

jQuery实现

// 监听图片加载完成
$('.card_img').on('load', function() {
  // jQuery的height()方法直接返回元素的显示高度(不含边框和内边距)
  const displayHeight = $(this).height();
  // 如果需要包含内边距用outerHeight(),包含外边距用outerHeight(true)
  console.log('图片显示高度:', displayHeight); // 输出222
});

// 处理缓存场景
if ($('.card_img')[0].complete) {
  console.log('图片显示高度(缓存):', $('.card_img').height());
}

这些方法能拿到正确的222,是因为我们读取的是图片元素在DOM中实际渲染后的尺寸,而非图片文件的原始naturalHeight(该值会是405)。容器的min-height属性仅影响容器的最小高度,不会干扰我们读取图片自身的显示高度。


内容的提问来源于stack exchange,提问作者Aafaq Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:18:12