因此,警报会给出宽度和高度的不确定值。我认为img.onload计算中图像的w和h值未传递给要返回的值,或者可能在onload计算它们 之前 返回了w和h :
function getMeta(url){ var w; var h; var img=new Image; img.src=url; img.onload=function(){w=this.width; h=this.height;}; return {w:w,h:h} } // "http://snook.ca/files/mootools_83_snookca.png" //1024x678 // "http://shijitht.files.wordpress.com/2010/08/github.png" //128x128 var end = getMeta("http://shijitht.files.wordpress.com/2010/08/github.png"); var w = end.w; var h = end.h; alert(w+'width'+h+'height');
如何让警报显示正确的宽度和高度?
function getMeta(url){ $("<img/>",{ load : function(){ alert(this.width+' '+this.height); }, src : url }); }
function getMeta(url){ var img = new Image(); img.onload = function(){ alert( this.width+' '+ this.height ); }; img.src = url; }
function getMeta(url){ var img = new Image(); img.addEventListener("load", function(){ alert( this.naturalWidth +' '+ this.naturalHeight ); }); img.src = url; }
只需将以上内容用作: getMeta( "http://example.com/img.jpg" );
getMeta( "http://example.com/img.jpg" );