2015-09-24 99 views
0

我有問題的寬度和高度。寬度和高度undefined - Javascript/jQuery

我的功能:

function testImageSize(testSrc) { 

    var imageTestLink = ""; 
    var link = testSrc.attr("src"); 

    link = link.replace("/thumbs/", "/images/"); 
    imageTestLink = link.replace(".thumb", ""); 

    var theImage = new Image(); 
    theImage.src = imageTestLink; 

    console.log(imageTestLink); 

    var rw = theImage.width; 
    var rh = theImage.height; 

    console.log(rw, rh); 

} 

我的問題是,當我運行這個功能imagesTestLink總是返回正確的鏈接到圖像。但是rwrh有時會在控制檯中返回0 0值。有人可以幫我解決這個問題嗎?我已經閱讀了很多主題,但我沒有找到我的答案。

問候, Fantazy

回答

1

的問題是,函數結束之前的圖像可能不會被加載。你需要以應對與使用回調...

var rw; 
var rh; 

function testImageSize(testSrc, callback) { 
    var imageTestLink = ""; 
    var link = testSrc.attr("src"); 

    link = link.replace("/thumbs/", "/images/"); 
    imageTestLink = link.replace(".thumb", ""); 

    var theImage = new Image(); 

    // create an event handler that runs when the image has loaded 
    $(theImage).on("load", function() { 
     rw = theImage.width; 
     rh = theImage.height; 
     callback(); 
    }); 

    console.log(imageTestLink); 

    theImage.src = imageTestLink; 
} 

testImageSize("/thumbs/thumbnail.jpg", function() { 
    // this function will only be executed once the image has loaded 
    console.log(rw, rh); 
}); 

基本上,你創建你想要當圖像加載運行的功能,你已經有了規模,你將其轉換爲testImageSize。加載圖像,一旦完成,它會得到大小,然後調用您通過的函數。