2011-03-04 84 views
3

Im在加载DOM后Chrome无法识别图片宽度或高度时遇到问题。该图像是通过phpThumb脚本(调整图像大小)动态加载的。如果我拿走了动态网址,并将其替换为图片的直接网址,我没有遇到任何问题,并且所有工作都在Chrome中运行,但是使用动态网址,Chrome似乎无法计算图片的宽度或高度。Jquery; Chrome Image Width and Height = 0 for new Image()

任何人都有这方面的经验? 。它做我的头

有问题的代码是:

var theImage  = new Image(); 
theImage.src  = $image.attr('src'); 
var imgwidth  = theImage.width; 
var imgheight = theImage.height; 

其中imgwidth = 0;对于Chrome而言,IE,Firefox都会报告正确的大小。

+3

它看起来并不像你必须在你调用这个时加载的任何图像。你知道如何等待图像加载来询问高度和宽度吗? – 2011-03-04 19:34:44

回答

5

权代码.onload及以下功能:

var theImage  = new Image(); 
theImage.src  = $image.attr('src'); 
theImage.onload = function(){ 
    var imgwidth  = $(this).width; 
    var imgheight = $(this).height; 
}); 
0

http://jsfiddle.net/cyrilkong/XJUGt/4/

function imgRealSize(img) { 
    var $img = $(img); 
    if ($img.prop('naturalWidth') === undefined) { 
     var $tmpImg = $('<img/>').attr('src', $img.attr('src')); 
     $img.prop('naturalWidth', $tmpImg[0].width); 
     $img.prop('naturalHeight', $tmpImg[0].height); 
    } 
    return { 
     'width': $img.prop('naturalWidth'), 
     'height': $img.prop('naturalHeight') 
    }; 
} 

$(function() { 
    var target = $('img.dummy'); 
    var target_native_width; 
    var target_native_height; 
    target.each(function(index) { 
     // console.log(index); 
     imgRealSize(this[index]); 
     target_native_width = $(this).prop('naturalWidth'); 
     target_native_height = $(this).prop('naturalHeight'); 
     $(this).parent('div').append('<p>This image actual size is ' + target_native_width + ' x ' + target_native_height + ', and css is ' + $(this).width() + ' x ' + $(this).height() + '.</p>'); 
    }); 
});​