Javascript img.width和img.height随机返回0

Javascript img.width和img.height随机返回0,javascript,html,Javascript,Html,多亏了现有的线程,我能够产生以下代码: var img = new Image(); img.src = imgSrc; if(imgSrc.substring(imgSrcLength-4, imgSrcLength) == '.ico'){ document.getElementById('size' + lineCount).innerHTML = img.height + 'x' + img.width; } else { document.getElementById(

多亏了现有的线程,我能够产生以下代码:

var img = new Image();
img.src = imgSrc;
if(imgSrc.substring(imgSrcLength-4, imgSrcLength) == '.ico'){
    document.getElementById('size' + lineCount).innerHTML = img.height + 'x' + img.width;
} else {
    document.getElementById('size' + lineCount).innerHTML = img.naturalHeight + 'x' + img.naturalWidth;
}
基本上可以忽略lineCount零件。它应该在html列表中显示不同图像的大小。但是,有时宽度或高度返回为0。对我来说,这似乎是随机的,因为如果我再次运行脚本,将加载正确的数量,而其他位置为0。如果我尝试通过Microsoft Edge函数调试代码,一切正常,不会出现任何0


这是我的Microsoft Edge造成的问题还是我遗漏了什么?

您需要等待图像完成加载,然后获取其大小。试着这样做:

var img = new Image();
img.onload = function () {
    if(imgSrc.substring(imgSrcLength-4, imgSrcLength) == '.ico'){
        document.getElementById('size' + lineCount).innerHTML = img.height + 'x' + img.width;
    } else {
        document.getElementById('size' + lineCount).innerHTML = img.naturalHeight + 'x' + img.naturalWidth;
    }
};
img.src = imgSrc;

您需要等待图像完成加载,然后获取其大小。试着这样做:

var img = new Image();
img.onload = function () {
    if(imgSrc.substring(imgSrcLength-4, imgSrcLength) == '.ico'){
        document.getElementById('size' + lineCount).innerHTML = img.height + 'x' + img.width;
    } else {
        document.getElementById('size' + lineCount).innerHTML = img.naturalHeight + 'x' + img.naturalWidth;
    }
};
img.src = imgSrc;

在计算代码时未加载图像时,图像的宽度和高度很可能返回0。请确保在运行代码之前加载了图像(即,通过在窗口的onLoad事件中运行代码)。

在评估代码时未加载图像时,图像的宽度和高度很可能返回0。请确保在运行您的代码之前加载了映像(即,通过在窗口的onLoad事件中运行代码)