2011-11-19 36 views
1

我正在寻找一种方法来加载页面上的几个隐藏的缩略图(大约500),计算它们的总宽度,并在全部加载后显示它们的容器。用回调加载几个图像()

问题是容器在全部加载之前一直显示。

下面是简单的代码片段,我从我的脚本中提取:

// $('#thumbScroller') is the container, and is initially hidden. 

var imgs = ['http://www.google.com/images/nav_logo95.png', 'http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4']; 

for(var i = 0; i < i.length; i++){ 
    var url = imgs[i]; 
    $('#thumbScroller').append('<img src="' + url + '" class="thumb" />'); 

    // all elements were appened at this point 
    if(i == $this.totalImages-1){ 

     //variable to hold total container width 
     var totalContent=0; 

     // loop through images to calculate total width 
     $('#thumbScroller img').each(function (s) { 
      totalContent += $(this).width(); 

      //last image, show interface elements 
      if(s == $('#thumbScroller img').length-1){ 
       $('#thumbScroller').width(totalContent).fadeIn(); 
      }; 

     }); 
    } 

} 

任何帮助,将不胜感激!

+0

将.hidden类添加到for之前的.interface元素。 –

回答

1
for(var i = 0; i < imgs.length; i++){ 
    var url = imgs[i]; 
    $('#thumbScroller').append('<img src="' + url + '" class="thumb" />'); 
} 
var imgCount = $('#thumbScroller img').length; 
var totalContent=0; 
$('#thumbScroller img').load(function() { 
    if (!--imgCount) { 
     $('#thumbScroller').width(totalContent); 
     $('.loader').removeClass('visible'); 
     $('.interface').removeClass('hidden'); 
    } else { 
     totalContent += $(this).width(); 
     console.log('continue...'); 
    } 
}); 
+0

是的! onload事件会诀窍。谢谢! – Pierre

+0

@Pierre thnx ... – thecodeparadox

1

由于隐藏元素没有宽度,因此您需要在执行计算时将元素移动到“离开页面”,然后在完成后将其移回。请注意,如果您无法移动容器,则可以在计算宽度时将图像添加到不同的“离页”容器,然后在完成后将它们移动到原始容器中。

var imgs = ['http://www.google.com/images/nav_logo95.png', 'http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4']; 

$('#thumbScroller').css({position: 'absolute', left: '-99999px'}); 

for(var i = 0; i < i.length; i++){ 
    var url = imgs[i]; 
    $('#thumbScroller').append('<img src="' + url + '" class="thumb" />'); 

    // all elements were appened at this point 
    if(i == $this.totalImages-1){ 

     //variable to hold total container width 
     var totalContent=0; 

     // loop through images to calculate total width 
     $('#thumbScroller img').each(function (s) { 
      totalContent += $(this).width(); 

      //last image, show interface elements 
      if(s == $('#thumbScroller img').length-1){ 
       $('#thumbScroller').width(totalContent); 
       $('.loader').removeClass('visible'); 
       $('.interface').removeClass('hidden'); 
      }; 

     }); 
    } 

} 


$('#thumbScroller').css({position: '', left: ''});