0

我将很多图像加载到我的网站,如果我有耐心,它可以正常工作。但有时我在图像加载过程中触发一个动作,myDiv.style.display = 'none';然后图像得到宽度=高度=0,因为所有图像都没有完成。当我让我的 div 再次可见时,我看不到它们,但通过搜索 width=height=0 来识别它们。

如果我将宽度和高度设置为大于 0 的值,我会看到图像,但这样会丢失实际大小。我还尝试通过添加类似 .src 的内容来更改 image.src myImage.src += "?t=random";。这样做,myImage.onload函数再次被触发,但宽度和高度仍然为 0。

如何获得图像的实际大小或如何强制重新加载?

4

2 回答 2

1

您可以将事件附加到图像元素:

image.onload = function () { /* Your code here */ };

这将在实际加载图像时触发。

确保在设置 src 元素之前附加此事件并确保您的 src 实际上是有效的。您可以在 Google Chrome 的网络面板中检查这一点(Windows 上的 F12)。

于 2014-08-01T17:01:24.113 回答
0

深入了解我发现以下解决方法。

第一次加载图像时,它具有有效的宽度和高度,但由于 div 不可见而无法绘制。当我使 div 再次可见并通过更改图像 URL 来启动重新加载时,就像图像宽度和高度myImage.src+="?t=random"image.onload0 时触发的一样。所以我能做的就是保存原始值并在需要时使用它们。

// save or reload image size in case of load interruption if (typeof this.orgWidth == 'undefined' && this.width>0) this.orgWidth = this.width; if (typeof this.orgHeight == 'undefined' && this.height>0) this.orgHeight = this.height; if (this.width==0) this.width=this.orgWidth; if (this.height==0) this.height=this.orgHeight;

于 2014-08-02T08:02:48.490 回答