2011-03-04 123 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>'); 
    }); 
});​