未定义的宽度和高度 - Javascript / jQuery

时间:2015-09-24 14:07:55

标签: javascript jquery dom

我的宽度和高度都有问题。

我的功能:

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 个答案:

答案 0 :(得分: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。加载图像,一旦完成,它就会获得大小,然后调用你传入的函数。