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

Width and height undefined - Javascript/jQuery

本文关键字:Javascript jQuery 未定义 高度      更新时间:2023-09-26

我有一个宽度和高度的问题。

我的函数:

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

问题是在函数结束之前图像可能不会被加载。你需要使用回调来处理…

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。它会加载图片一旦完成它会获取图片的大小然后调用你传入的函数