2014-02-07 61 views
0

我正在處理一個燈箱,我需要獲取要顯示的圖像元素的原始尺寸。我正在研究基於CSS-Tricks的基於off this tutorial的方法。我的圖片原生爲400x400像素,但我的方法一直返回0x0。下面是相關的代碼:爲什麼這不會得到圖像的原生尺寸?

function setLuxboxSize() { 
    console.log("picture original: " + luxpic.attr('src')); 

    var testingImage = new Image(); 

    testingImage.src = luxpic.attr('src'); 

    //console.log('testingImage src:' + testingImage.attr('src')); 


    var picWidth = testingImage.width; 
    var picHeight = testingImage.height; 


    console.log("original width: " + picWidth); 
    console.log("original height: " + picHeight); 
}; 

此外,當註釋掉的console.log線是積極的,我收到以下錯誤控制檯:遺漏的類型錯誤:對象#有沒有方法「ATTR」。第一個console.log行按預期返回一個src。我究竟做錯了什麼?

編輯:問題是圖像尚未加載,寬度和高度調用將不會返回正確的值,直到它。檢查LorDex或Satpal的答案,以使用onload函數獲取尺寸。

+0

什麼是'luxpic' var?你的代碼期望它是一個包裝的jQuery結果,就像'var luxpic = $(「#image」);' – Will

+0

哦,是的東西是在其他地方定義的,我沒有出來這部分雖然:) – Ber

回答

0

您必須先載入圖像,然後才能檢查其尺寸。

var testingImage = new Image(); 
testingImage.src = luxpic.attr('src'); 
testingImage.onload = function() { 
    var picWidth = this.width; 
    var picHeight = this.height; 

    console.log("original width: " + picWidth); 
    console.log("original height: " + picHeight); 
}; 
+0

謝謝你的作品! – Ber

1

您可以檢查加載後的實際圖像大小。爲了做到這一點,請使用.onload()方法:

testingImage.onLoad(function() { 
    var picWidth = testingImage.width; 
    var picHeight = testingImage.height; 
    console.log("original width: " + picWidth); 
    console.log("original height: " + picHeight); 
}); 
+0

感謝那個完美工作的人。 – Ber