【问题标题】:Show loader GIF meanwhile a div is loading在加载 div 的同时显示加载器 GIF
【发布时间】:2014-10-09 03:55:52
【问题描述】:

嗨,我在点击时显示了一个 div,但是这个 div 的内容是一些非常大的图像,我想在 div 加载的同时添加一个预加载器......我一直在尝试使用 jquery .load 但只能得到它在第一次加载页面而不是点击时工作。

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

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

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

【问题讨论】:

  • 如果是图片需要时间加载,您必须在图片上挂钩加载。见stackoverflow.com/questions/10790226/jquery-image-load-callback
  • 事情是我使用背景图片,它是整个 div 需要时间来加载.. 我不知道如何在 div 上附加 .load 事件
  • 我试过这样做,但它不起作用 $('#aboutContent').load(function() { jQuery("#gif").show(100); }) ;

标签: javascript jquery html


【解决方案1】:

你可以在图片上绑定load事件,图片一加载就会触发。

$("#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);
        }

    });
});

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多