我正在寻找一种方法来在页面上加载几个隐藏的缩略图(大约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 :(得分: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...');
}
});
答案 1 :(得分: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: ''});