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

如何在网页图片旁显示尺寸?编写的JS代码无效果求排查

图片原始尺寸获取失败的问题排查与修复

问题背景

想要在图片旁显示它的原始尺寸(比如300x400),写了一段混合原生JS和jQuery的代码放在head标签里,但完全没效果,拿不到naturalWidth和naturalHeight:

脚本代码:

<script>
    document.addEventListener('DOMContentLoaded', function (onload) {
var el = document.getElementById("#imgdim");
var txt = + $("#imgdim").naturalWidth() + "x" + + 
$("#imgdim").naturalHeight();
console.log({
"naturalWidth": el.naturalWidth,
"naturalHeight": el.naturalHeight,
});
})
</script>

对应的图片标签:

<img id="imgdim" src="getimg.php?id='.$irow["id"].'"></div>

问题出在哪?

  • getElementById参数写错了:原生JS的这个方法只需要传纯ID字符串,不能加#前缀,你写"#imgdim"会导致el是null,后面访问el.naturalWidth直接报错。
  • jQuery没有naturalWidth()方法:naturalWidth和naturalHeight是原生DOM元素的属性,不是jQuery对象的方法,你调用$("#imgdim").naturalWidth()会直接报错“不是函数”。
  • 时机不对:DOMContentLoaded只是DOM解析完了,图片可能还没加载好,这时候naturalWidth和naturalHeight可能返回0,拿不到真实尺寸。
  • 没做显示逻辑:原代码只在控制台打了日志,根本没把尺寸文本插到页面里,就算拿到了也看不到。

修复后的代码示例

原生JS版本

<script>
document.addEventListener('DOMContentLoaded', function() {
    const img = document.getElementById('imgdim');
    // 等图片加载完成再获取尺寸
    img.addEventListener('load', function() {
        const width = this.naturalWidth;
        const height = this.naturalHeight;
        // 创建尺寸文本元素
        const sizeSpan = document.createElement('span');
        sizeSpan.textContent = `${width}x${height}`;
        // 把尺寸放在图片旁边
        img.parentNode.insertBefore(sizeSpan, img.nextSibling);
        console.log({ naturalWidth: width, naturalHeight: height });
    });
    // 处理图片缓存的情况:如果图片已经加载完,手动触发load事件
    if (img.complete) {
        img.dispatchEvent(new Event('load'));
    }
});
</script>

jQuery混合版本

<script>
$(document).ready(function() {
    const $img = $('#imgdim');
    const imgDom = $img[0]; // 拿到原生DOM元素
    // 监听图片加载
    $img.on('load', function() {
        const width = imgDom.naturalWidth;
        const height = imgDom.naturalHeight;
        // 直接生成HTML插入到图片后面
        $img.after(`<span>${width}x${height}</span>`);
        console.log({ naturalWidth: width, naturalHeight: height });
    });
    // 处理缓存
    if (imgDom.complete) {
        $img.trigger('load');
    }
});
</script>

内容的提问来源于stack exchange,提问作者Siamak Ensafi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:20:21