2011-11-19 59 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: ''});