Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript/jquery中获取图像的完整大小_Javascript_Jquery_Image_Resize - Fatal编程技术网

在javascript/jquery中获取图像的完整大小

在javascript/jquery中获取图像的完整大小,javascript,jquery,image,resize,Javascript,Jquery,Image,Resize,我在页面上有一个图像,它的大小已经调整到适合一个div,比如400x300。如何在jQuery中获得图像的完整大小(~4000x3000)。width()和.height()似乎只返回图像的当前大小。您可以使用包含相同源文件的图像对象执行此操作,如: var preloader = new Image(); preloader.src = 'path/to/my/file.jpg'; preloader.onload = function(){ var height = preloader.h

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

您可以使用包含相同源文件的
图像
对象执行此操作,如:

var preloader = new Image();
preloader.src = 'path/to/my/file.jpg';

preloader.onload = function(){
var height = preloader.height;
var width = preloader.width;
}
试试这个:

变量pic=$(“img”)

//如果img元素设置了宽度和高度,则需要移除这些 图:拆卸器(“宽度”); 图:拆卸器(“高度”)

var pic_real_width=pic.width();
var pic_real_height=pic.height()

您可以克隆图像,删除高度和宽度属性,将其附加到主体,并在删除之前获取宽度和大小

JSFIDLE演示在这里:

代码是:

$(function() {
   var img = $('#kitteh'); // image selector
   var hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
    $('#height').text(hiddenImg.height());
    $('#width').text(hiddenImg.width());
    hiddenImg.remove();            
});​

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

不过,人们仍然需要等待图像加载

$('#idOfMyimg').on('load', function() {
    var height = this.naturalHeight,
        width  = this.naturalWidth;
});
另一种选择是使用与源文件相同的文件创建新图像,并从中获取尺寸,只要它从未添加到DOM中,外部样式不会影响它

var img = new Image();

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

必选猫咪图片的道具:)@npc Thx!我甚至不是一个“爱猫的人”,但在罗马时…:-)+对于另一个不同的解决方案:)很好的解决方案。此外,我将样式属性width和height设置为auto:img.clone().css({visibility:'hidden',width:'auto',height:'auto'})我已经编辑了我的答案,现在它将在ur[jsfiddle.net/kCN2x]链接上运行plz检查快速而完美的解决方案,而不会牺牲性能