我的宽度和高度有问题。
我的功能:
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
时始终返回正确的图像链接。但是rw
和rh
有时返回0 0
控制台中的值。有人可以帮我解决这个问题吗?我已经阅读了很多主题,但没有找到答案。
问候, 幻想
最佳答案
问题是在函数结束之前图像可能无法加载。您需要使用回调来处理该问题...
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
。这会加载图像,一旦完成,它就会获取大小,然后调用您传入的函数。
关于javascript - 宽度和高度未定义 - Javascript/jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32763540/