有时,图像需要一些时间才能在浏览器中呈现.我想在下载实际图像时显示忙图像,下载图像时,将删除忙图像并显示实际图像.我怎么能用JQuery或任何javascript做到这一点?
Ger*_*ben 160
只需使用css为所有图像添加背景图像:
img {
background: url('loading.gif') no-repeat;
}
Run Code Online (Sandbox Code Playgroud)
Sar*_*raz 95
你可以这样做:
// show loading image
$('#loader_img').show();
// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});
Run Code Online (Sandbox Code Playgroud)
您将load事件分配给图像加载完成时触发的图像.在此之前,您可以显示您的加载程序图像.
Set*_*eth 11
我使用与@Sarfraz发布的类似的技术,除了隐藏元素,我只是操纵我正在加载的图像的类.
<style type="text/css">
.loading { background-image: url(loading.gif); }
.loaderror { background-image: url(loaderror.gif); }
</style>
...
<img id="image" class="loading" />
...
<script type="text/javascript">
var img = new Image();
img.onload = function() {
i = document.getElementById('image');
i.removeAttribute('class');
i.src = img.src;
};
img.onerror = function() {
document.getElementById('image').setAttribute('class', 'loaderror');
};
img.src = 'http://path/to/image.png';
</script>
Run Code Online (Sandbox Code Playgroud)
在我的情况下,有时图像不会加载,所以我处理onerror事件来更改图像类,以便它显示错误的背景图像(而不是浏览器的损坏的图像图标).