export const getImgSize = function (img, callback) { if (!(img instanceof HTMLImageElement)) { throw new Error('Invalid image element'); } if (img.naturalWidth) { // 现代浏览器 callback({ w: img.naturalWidth, h: img.naturalHeight }); } else { // IE6/7/8 var image = new Image(); image.src = img.src; image.onload = function () { callback({ w: image.width, h: image.height }); }; image.onerror = function () { console.error('There was an error loading the image.'); }; } };
-
获取是图片的实际尺寸,不受 CSS 影响的原始尺寸
-
对于现代浏览器,直接使用
naturalWidth
和naturalHeight
属性即可,无需创建新的Image
对象。对于旧版 IE 浏览器,确保不会重复加载图像。