首页 > 解决方案 > 如何防止浏览器的 img 绘画可见?

问题描述

当我向 DOM 添加新图像时,有时我可以看到图像是从上到下绘制的。是否有一种简单的 javascript 技术或事件处理程序可用于仅在浏览器完成绘制/渲染后才显示完整图像?

标签: javascripthtmlcssimageevent-handling

解决方案


You could use JavaScript to hide the image until it is fully loaded.

HTML:

<img id="image" src="...">

JavaScript:

var image = document.querySelector('#image');

image.style.opacity = '0'; //set opacity to 0 (fully transparent)

image.onload = function(){ //when image is loaded, execute function
    image.style.opacity = '1'; //set opacity to 1 (fully visible)
}

Because I use opacity property in this example, you could even animate the image appearing.

CSS:

#image {
    transition: opacity .5s;
}

推荐阅读