在javascript / jquery中获取完整大小的图像 [英] Get full size of image in javascript/jquery

查看:139
本文介绍了在javascript / jquery中获取完整大小的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有一个图像已调整大小以适合div,例如400x300。如何在jQuery中获得图像的完整大小(~4000x3000)? .width()和.height()似乎只返回图像的当前大小。

I have an image on page that has been resized to fit in a div, say, 400x300. How can I get the full size of the image (~4000x3000) in jQuery? .width() and .height() only seem to return the current size of the image.

推荐答案

图像有 naturalWidth naturalHeight 属性包含图像的实际未修改宽度和高度,即图像的实际尺寸,而不是CSS设置它。

Images have naturalWidth and naturalHeight properties that contain the actual, non-modified width and height of the image, i.e. the real dimensions of the image, not what CSS sets it to.

仍然需要等待图像加载

$('#idOfMyimg').on('load', function() {
    var height = this.naturalHeight,
        width  = this.naturalWidth;
});

另一种选择是使用与源相同的文件创建新图像,并获取尺寸从那以后,只要它从未添加到DOM,外部样式就不会影响它

Another option would be to create a new image with the same file as the source, and get the dimensions from that, as long as it's never added to the DOM, not external styles will affect it

var img = new Image();

img.onload = function() {
   var height = this.height,
       width  = this.width;
}
img.src = $('#idOfMyimg').attr('src');

FIDDLE

这篇关于在javascript / jquery中获取完整大小的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆