J’ai un code très simple, qui fonctionnait ennuyeusement et pour la vie de moi je ne vois pas pourquoi il échoue maintenant
function imageSize(img){ var theImage = new Image(); theImage.src = img.attr('src'); var imgwidth = theImage.width; var imgheight = theImage.height; alert(imgwidth+'-'+imgheight); }
La variable “img” transmise est l’object img, obtenu à partir de:
jQuery('img') .each(function(){ var imgsrc = jQuery(this); imageSize(imgsrc); });
L’image n’est peut-être pas encore chargée. Alors, essayez (non testé):
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'); }
Ok – la réponse précédente que je donnais était invalide quand je l’ai testée sur jsFiddle – j’ai créé ce qui fait ce que tu veux? Avez-vous besoin de la partie “nouvelle Image ()”? http://jsfiddle.net/R89Qr/3/ – a donné aux images des dimensions codées en dur …
J’ai légèrement changé votre code, de sorte qu’il fasse ceci:
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); });
Vous devez attendre jusqu’à ce que votre image soit chargée, puis accédez à ses tailles:
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'); }