2012-03-20 85 views
1

我有一個非常簡單的代碼,這煩人的是工作,我的生活中,我看不出爲什麼它現在失敗:獲取圖像的寬度和高度與jQuery

function imageSize(img){ 
    var theImage = new Image(); 
    theImage.src = img.attr('src'); 
    var imgwidth = theImage.width; 
    var imgheight = theImage.height; 

    alert(imgwidth+'-'+imgheight); 
} 

的「IMG」變量存在通過從獲得的IMG對象:

jQuery('img') 
.each(function(){ 
    var imgsrc = jQuery(this); 
    imageSize(imgsrc); 
}); 
+0

那麼,究竟是什麼問題呢?看起來沒問題。另外,你爲什麼使用完整的單詞'jQuery'?兼容性問題?你爲什麼不使用'$'? – 2012-03-20 13:20:35

+1

值得一提的是,如果在代碼運行時圖像沒有完全下載,那麼寬度和高度將返回爲零,或者可能是其他一些不正確的值。 – Blazemonger 2012-03-20 13:20:37

+0

準確檢測圖像何時完全加載非常棘手,因爲如果從緩存中提取圖像,'.load'事件不會觸發。請參閱[此問題](http://stackoverflow.com/q/3554185/901048)以獲取解決方案。 – Blazemonger 2012-03-20 13:23:36

回答

2

圖像可能尚未加載。所以,試試(未經測試):

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'); 
} 
+0

非常感謝 – xtremetom 2012-03-20 13:25:36

2

好了 - 以前的答案我給無效時,我測試的jsfiddle - 我創造了這個它,你想要做什麼,雖然?你需要需要有「新的圖像()」部分? http://jsfiddle.net/R89Qr/3/ - 給一些圖片尺寸硬編碼...

我稍微改變你的代碼,使之做到這一點:

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); 
}); 
+1

如果'theImage'是一個jQuery對象,那會是真的。 – Blazemonger 2012-03-20 13:21:22

+0

是的 - v.true,我做了一些改動,並添加了一個小提琴讓它工作。 – SpaceBison 2012-03-20 13:24:20

+0

你在吠叫錯誤的樹。非jQuery JavaScript [圖像對象](http://www.w3schools.com/jsref/dom_obj_image.asp)具有應該在原始代碼示例中檢索到的寬度和高度屬性 - 如果圖像已完全加載代碼運行的時間。 – Blazemonger 2012-03-20 13:27:28

1

你必須等待,直到你的形象將被加載,然後進入其尺寸:

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'); 

}