您的位置:首页 > Web前端 > JavaScript

使用JavaScript获取图片的真实尺寸大小

2014-12-25 00:47 471 查看
Webkit 内核的浏览器在加载完图片之后才能获取宽和高。所以,我建议使用onload时间来获取图片的宽和高

var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width;   // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});


上面的代码使用内存去存储图片来计算宽与高,所以不用担心图片因为css设置而尺寸发生了变化。

参考:http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: