0

我正在处理引导栏预加载页面上的图像。事情工作正常,但我不知道如何使所有图像加载后进度条消失。这里是我的代码:如何隐藏所有图像加载后的进度条

<div class="progress progress-info progress-striped active"> 
    <div class="bar" id='fabbar' style="width: 20%">0%</div> 
</div> 
<img src="http://placekitten.com/1000/1000" alt="" width="100" height="100" /> 
<img src="http://placehold.it/1000x1000" alt="" width="100" height="100" /> 
<img src="http://placebear.com/1000/1000" alt="" width="100" height="100" /> 
<img src="http://lorempixel.com/1000/1000" alt="" width="100" height="100" /> 
<img src="http://placedog.com/1000/1000" alt="" width="100" height="100" /> 

JS

$(function() { 
    var n = 0, 
     $imgs = $('img'), 
     val = 100/$imgs.length, 
     $bar = $('#fabbar'); 

    $imgs.load(function() { 
     n = n + val; 
     // for displaying purposes 
     $bar.width(n + '%').text(n + '%'); 
$('#imgLoader').hide(); 
    }); 
}); 

现在我有2个问题。

  1. 在加载之前,整个酒吧都消失了。
  2. 什么函数可以使百分比数字如20%,40%,100%。现在是93.33333333333334%。
+0

[请参考此处。它似乎是你的问题的一个可靠的解决方案,除了百分比](http://stackoverflow.com/questions/2832953/jquery-check-when-image-is-loaded) –

回答

1

对于你的第一个问题,你可以使用jQuery的$.Deferred来允许你的函数调用另一个函数,而不是异步运行。它可以将多个回调注册到回调队列中,调用回调队列并转发任何同步或异步功能的成功或失败状态。 您的代码看起来与此类似:

var FunctionOne = function() { 
    // create a deferred object 
    var r = $.Deferred(); 

// do whatever you want (e.g. ajax/animations other asyc tasks) 
// and call `resolve` on the deferred object, once you're done 
r.resolve(); 
// return the deferred object 
return r; 
}; 

// define FunctionTwo as needed 
var FunctionTwo = function() { 
    $('#imgLoader').hide(); 
}; 

// call FunctionOne and use the `done` method 
// with `FunctionTwo` as it's parameter 
$(function() { 
    FunctionOne().done(FunctionTwo); 
})