2012-03-23 19 views
0

使用jquery如何显示加载gif,直到图像完全加载,然后删除加载gif并显示实际图像。这应该独立发生在页面内的所有图像上。这里有一个例子:使用jquery:为每个图像加载显示一个ajax加载gif,直到该非视图图像完全加载

http://jwt.com/

这是我尝试它似乎不工作:

HTML

<div class="thumbnail"><a href="#" class="boxImage ajaxloader"><img src="...image-one..." /></a></div> 
<div class="thumbnail"><a href="#" class="boxImage ajaxloader"><img src="...image-two..." /></a></div> 
<div class="thumbnail"><a href="#" class="boxImage ajaxloader"><img src="...image-three..." /></a></div> 

CSS

.ajaxloader{ background: transparent url(..ajax-loader.gif...) no-repeat scroll center center; 

JS

$('a.boxImage img').one("load", function(){ 
     $(this).parent().removeClass('ajax-loader'); 
    }).each(function(){ 
     //covering the case images loading from cache 
     if(this.complete){ 
      $(this).trigger("load"); 
      $(this).parent().removeClass('ajax-loader'); 
     } 
    }); 

另一个问题......上述方法(例如,解决问题后)只允许一次加载一个图像,还是允许浏览器对图像发出多个请求并加载尽可能多的图像在平行下。

回答

0

不知道这是否会成功,但是这是一个更好的版本的你已经拥有:

$('a.boxImage img').on("load", function(){//Note: .on() not .one() 
    $(this).parent().removeClass('ajax-loader'); 
}).each(function(){ 
    //covering the case images loading from cache 
    if(this.complete){ 
     $(this).trigger("load"); 
     //No need to repeat the code; triggering the load handler does the job. 
    } 
}); 

你可能会与浏览器(需设置)显示图像占位符(部分)的问题了加载动画。出于这个原因,最好使用额外的<img>元素(每个缩略图一个)。从加载动画显示开始并隐藏真实图像,然后当真实图像的加载事件触发时,隐藏动画并显示真实图像。

$('a.boxImage img.real').on("load", function(){ 
    $(this).show().siblings('img.loading').hide(); 
}).each(function(){ 
    //covering the case images loading from cache 
    if(this.complete){ 
     $(this).trigger("load"); 
    } 
}); 

你还需要确保容器和/或加载图像的尺寸以同样大小的缩略图,这样当切换发生时没有大小的变化。你可能已经在CSS中看到了,我看不到。

相关问题