2015-09-24 48 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。加载图像,一旦完成,它会得到大小,然后调用您通过的函数。