Getting image width and height with jquery

大城市里の小女人 提交于 2019-12-19 11:29:37

问题


I have a very simple code, which annoyingly was working and for the life of me I can not see why it is now failing:

function imageSize(img){
  var theImage = new Image();
  theImage.src = img.attr('src');
  var imgwidth = theImage.width;
  var imgheight = theImage.height;

  alert(imgwidth+'-'+imgheight);
}

The "img" variable being passed is the img object, obtained from:

jQuery('img')
.each(function(){
    var imgsrc = jQuery(this);
    imageSize(imgsrc);
});

回答1:


The image may not have loaded yet. So, try (untested):

function imageSize(img){
  var theImage = new Image();
  $(theImage).load(function() {
    var imgwidth = this.width;
    var imgheight = this.height;

    alert(imgwidth+'-'+imgheight);
  });
  theImage.src = img.attr('src');
}



回答2:


Ok - the previous answer I gave was invalid when I tested it on jsFiddle - I created this which does what you want though? Do you need to have the "new Image()" part? http://jsfiddle.net/R89Qr/3/ - gave the images some hardcoded dimensions...

I changed your code slightly, so that it does this:

 function imageSize(img){
  var theImage = new Image(); // ignoring this part when checking the image width/height
  theImage.src = img.attr('src');
  var imgwidth = $(img).width();
  var imgheight = $(img).height();

  alert(imgwidth+'-'+imgheight);
}

$('img').each(function(){
    var imgsrc = jQuery(this);
    imageSize(imgsrc);
});



回答3:


You have to wait , till your image will be loaded , and then access to its sizes:

function imageSize(img){
  var theImage = new Image();
  theImage.onload = function(){
    var imgwidth = theImage.width;
    var imgheight = theImage.height;

    alert(imgwidth+'-'+imgheight);
  }
  theImage.src = img.attr('src');

}


来源:https://stackoverflow.com/questions/9787511/getting-image-width-and-height-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!