onLoad返回0作为宽度和高度

onLoad return 0 as width and height

本文关键字:高度 返回 onLoad      更新时间:2023-09-26

我正在尝试构建一个简单的图像预加载,它创建一个图像元素并存储它,这样我以后就可以立即使用它。

我已经设置了这个相当简单的singleton类,我可以在任何地方使用它:

var Preloader = (function() {
var instance = null;
function PrivateConstructor() {
    var total = 0;
    var onComplete = null;
    this.loadImages = function(images, completeHandler) {
        total = images.length;
        onComplete = completeHandler;
        for(var i = 0; i < images.length; i++) {
            var img = new Image();
            img.onLoad = this.onLoad(img);
            img.src = images[i];
        }
    }
    this.onLoad = function(img) {
        console.log(img);
        console.log(img.width);
        console.log(img.height)
        total--;
        if(total == 0) onComplete();
    }
}
return new function() {
    this.getInstance = function() {
        if (instance == null) {
            instance = new PrivateConstructor();
            instance.constructor = null;
        }
        return instance;
    }
}
})()

现在,当我使用这个并检查我的宽度和高度时,它仍然是0

Preloader.getInstance().loadImages(['https://si0.twimg.com/profile_images/188302352/nasalogo_twitter_bigger.jpg'], function() {
    console.log('images loaded');
});
// output
<img src="https://si0.twimg.com/profile_images/188302352/nasalogo_twitter_bigger.jpg">
0
0

在行中:

img.onLoad = this.onLoad(img);

您错误地立即调用this.onLoad,而不是将该函数作为加载处理程序传递。这样,您的代码就完成了,而无需等待实际加载图像。

您也有错误的情况-处理程序属性应该被称为img.onload,而不是img.onLoad

请注意,调用.onload事件处理程序时,会将图像作为其this上下文变量,而不是将其作为参数传递,因此您将在该事件处理程序中使用this(表示图像,而不是您的类)。

另一种选择是写:

var self = this;
img.onload = function() {
    self.onLoad(this);
}