onLoad和.load()函数中的图像宽度总是0

Image width in onLoad and .load() functions always 0

本文关键字:图像 load 函数 onLoad      更新时间:2023-09-26

我已经阅读了大量的帖子和文章,并尝试了JS-only onLoad方法和使用JQuery的。load(function(){的方式去做的事情,但我找不到一个好方法来加载图像悄悄地在后台,然后做一些一旦我知道它的实际宽度。

至此,我已经尽可能简单地得到了它,它仍然返回"0":

bgImg = new Image();
bgImg.src = "./img/car-and-truck.gif";
bgImg.onload = imageLoaded();
function imageLoaded() {
    alert(bgImg.width);
}

用这个代替:

bgImg.onload = imageLoaded;

您正在立即调用imageLoaded,而您并不想这样做。