显示加载器GIF同时加载div

时间:2014-08-15 11:56:41

标签: javascript jquery html

嗨我在点击时显示div,但是这个div的内容是一些相当大的图像,我想添加一个preloader同时div正在加载...我一直在尝试使用jquery .load但是只能得到它在加载页面时起作用而不是单击时起作用。

所以我希望在加载所有内容id #aboutcontent时点击并隐藏aboutclick时显示加载器gif。

function aboutClick(){
        $('#workContent').fadeOut(400,'easeInQuint');
        $('#aboutContent').fadeIn(400,'easeInQuint');       
 };

$('#aboutContent').load(function() {
   jQuery("#gif").show(100);
});

1 个答案:

答案 0 :(得分:1)

您可以在图像上绑定加载事件,它会在图像加载后立即触发。

$("#aboutContent img").load(function(){
  $("#loadergif").fadeOut(400);
});

然而,这将失败,因为如果您加载多个图像,加载第一个图像后,加载程序gif将立即隐藏。

这就是为什么你需要对图像数量保持一个计数器,并在它们完成加载后隐藏它。

取自:jquery callback after all images in dom are loaded?

$(function() {
    function imageLoaded() {
       // function to invoke for loaded image
       // decrement the counter
       counter--; 
       if( counter === 0 ) {
           // counter is 0 which means the last, so hide the loadergif
               $("#loadergif").fadeOut(400);
       }
    }
    var images = $('img');
    var counter = images.length;  // initialize the counter

    images.each(function() {
        if( this.complete ) {
            imageLoaded.call( this );
        } else {
           $(this).one('load', imageLoaded);
        }

    });
});
祝你好运。