0

我有一个 javascript 预加载器,它将图像数组加载到我的页面,然后在完成后执行回调函数。

在预加载期间,我想将当前预加载的图像附加到加载框中的 HTML 页面。这是我当前的代码。当前代码不适用于每个图像,而只是显示最后加载的图像的名称。我可以做些什么来修复我的预加载器函数,以便在每个循环中将正确的名称附加到我的 div 中?

    // Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {

  checklist = this.toArray();

  this.each(function() {
    $('div.circleText').html('<p>' +  this + '</p>');

    $('<img>').attr({ src: this }).load(function() {

      checklist.remove($(this).attr('src'));
      if (checklist.length == 0) { callback(); }
    });
  });
};

$([

'../img/about/01-inner-small.png',
'../img/about/01-small.png',
'../img/about/blue-gear.png',
'../img/about/orange-gear.png',
'../img/about/slimeGoblin.png',
'../img/about/03-small.png',
'../img/about/slideshow_back.png',
'../img/about/services_octopus.png',
'../img/about/services_pinkblur.png',
'../img/about/services_blur.png',
'../img/about/services_seahorse.png',
'../img/about/services_coral.png',
'../img/about/water3.png',
'../img/about/water2.png',
'../img/about/water1.png',
'../img/about/02-inner.png',
'../img/about/slime-glow.png',
'../img/about/02_longPhoto.png',
'../img/about/photo1.jpg',
'../img/about/orange-gear.png',
'../img/about/blue-gear.png',
'../img/about/01-small.png',
'../img/about/01.png',
'../img/about/slime-transparent.png',
'../img/about/slime.png',
'../img/about/02-small.png',
'../img/about/02.png',
'../img/about/01_head.png',
'../img/about/services_squid.png',
'../img/about/services_crabs.png',
'../img/about/02-small.png'

]).preloadImages(function(){ 
    // $('#loading').transition({ opacity: 0 }, 1000,'in-out',      
    //  function()
    //  { 
    //      $('#loading').hide();
    //  })
});
4

2 回答 2

0

您的代码运行良好,只是因为它发生得如此之快,您没有意识到这一点。替换以下行:

$('div.circleText').html('<p>' + value + '</p>');

有了这个:

setTimeout(function() {
    $('div.circleText').html('<p>' + value + '</p>');
}, 1000 + (index * 100));

这将确保您在处理数组时看到每个数组对象。当然,您可以根据需要调整每个可见的时间。

演示

于 2012-09-10T03:45:01.377 回答
0

上面的解决方案没有解决问题,只是显示。

正确答案在这里:http: //jsfiddle.net/ES8kw/1/

.load()功能不好。

.load(function() {
                delete checklist[$.inArray($(this).attr('src'),checklist)];
                $('#loading').html('<p>' + $(this).attr('src') + '</p>');
                var done = 0;
                $.each(checklist,function(i){ if(typeof checklist[i] == "undefined") { done++; }})
                if (checklist.length == done) {
                  callback();
              }
          });

所有这些都需要包装在一个setTimeout

于 2012-09-10T04:47:37.577 回答