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

如何使用JavaScript/jQuery在IE浏览器中获取图像宽高并完成图像校验?

获取页面图像尺寸的可用方法

原生JavaScript实现

  • 获取已加载完成图片的原始尺寸:
    直接使用naturalWidth和naturalHeight属性,这两个属性返回的是图片本身的原始分辨率,不受页面CSS缩放的影响,是最准确的取值方式。
    代码示例:
// 获取页面内第一个img元素
const targetImg = document.querySelector('img');
// 取原始尺寸
const imgOriginalWidth = targetImg.naturalWidth;
const imgOriginalHeight = targetImg.naturalHeight;
console.log(imgOriginalWidth, imgOriginalHeight);
  • 动态加载的图片/未完成加载的图片取尺寸:
    需要绑定load事件,等图片资源加载完成后再取值,否则会得到0值。
    代码示例:
const tempImg = new Image();
// 填入要获取尺寸的图片地址
tempImg.src = '你的图片资源地址';
tempImg.onload = function() {
  // 加载完成后取原始尺寸
  console.log(this.naturalWidth, this.naturalHeight);
};

jQuery实现

jQuery本身没有专门封装图片尺寸获取的API,可以直接调用DOM元素的原生属性取值:
代码示例:

// 取页面内第一个img元素的原始尺寸
const $targetImg = $('img').eq(0);
const imgOriginalWidth = $targetImg[0].naturalWidth;
const imgOriginalHeight = $targetImg[0].naturalHeight;

// 针对未加载完成的图片绑定事件
$('img').on('load', function() {
  console.log(this.naturalWidth, this.naturalHeight);
});

注意事项

  • 不要使用offsetWidth、clientWidth或者jQuery的width()方法取值,这些属性获取的是图片在页面上渲染后的尺寸,如果图片被CSS缩放、设置了最大宽高限制,拿到的值会和原始尺寸不一致。
  • 跨域图片如果没有配置CORS跨域许可,会因为浏览器同源策略限制无法正常获取尺寸属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:21:03