2013-04-18 55 views
18

所以我創建一個新的形象元素,一旦我得到來自AJAX調用響應與圖像元數據,這樣的收益0 ()函數返回0,儘管圖像的大小爲30 x 30像素,並且它在頁面上正確顯示。我需要獲得它的尺寸以絕對定位圖像。jQuery的寬度()和高度()爲img元素

+0

嘗試$(窗口).load(函數(){VAR 寬度= image.width(); VAR height; image.height(); console.log(width); console.log(height); }); –

回答

46

您需要等到圖像加載才能訪問寬度和高度數據。

var $img = $('<img>'); 

$img.on('load', function(){ 
    console.log($(this).width()); 
}); 

$img.attr('src', file.url); 

或用純JS:

var img = document.createElement('img'); 

img.onload = function(){ 
    console.log(this.width); 
} 

img.src = file.url; 

而且,你並不需要,將圖像插入到DOM你讀的寬度和高度值之前,所以你可以留下你的.loading-image直到更換計算完所有正確的位置後。

+0

感謝您的普通JS代碼。 – dstr

+1

這裏的jQuery代碼不適用於我,但很簡單,至少在Chrome v51.0.2704使用jQuery 1.12.4。它應該工作。的console.log($(本).WIDTH());記錄0無論如何,在寬度方法的實現中可能會有些奇怪。訪問寬度屬性通過console.log($(this)[0] .width);或者如果你想使用jQuery:console.log($(this).prop(「width」)); –

+0

@StephenBrown無論如何嘗試使用$(this).width(),我都會得到0。 – sandre89

7

這是因爲未加載圖片時您檢查寬度

嘗試使用Load事件這樣

$('img').on('load',function(){ 
    // check width 
}); 
-3

如果你把它的AJAX調用內,將工作過,這是JSON的方法

$.post("URL",{someVar:someVar},function(data){ 

    var totalImgs = $('body').find('img').length; 

    var image = $('<img src="' + data.file[0].url + '" alt="" id="IMG_'+ totalImgs +'">'); 

    loadedImageContainter.append(image); 
    $('.loading-image').replaceWith(loadedImageContainter); 

    var width = $('#IMG_'+totalImgs).width(); 
    var height = $('#IMG_'+totalImgs).height(); 

},'json'); 
-1

試試這個:

$('.loading-image').replaceWith(loadedImageContainter); 
$('.loading-image').load(function(){ 
    var width = image.width(); 
    var height = image.height(); 
    console.log(width); 
    console.log(height); 
}); 
0

您也可以使用備用API $.load方法:

$('<img src="' + file.url + '" alt="">').load(function(){ <your function implementation> }); 
0

由於@ahren said較早的原因是,當你特林得到它的大小不會加載該圖像。

如果要解決這個問題,而不jQuery的你可以用香草JS addEventListener方法:

document.getElementsByTagName('img')[0].addEventListener('load', function() { 
    // ... 
    var width = image.width(); 
    var height = image.height(); 
    console.log(width); 
    console.log(height); 
    // ... 
});