4

我尝试在图像加载时使用引导 css 制作进度条。为此,我使用以下脚本:

<html>
<head>
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet"/>
<script type="text/javascript">

var n=0;
var c=0;

$('img').each(function() {
    n++; 
    var tmpImg = new Image() ;
    tmpImg.src = $(this).attr('src') ;
    tmpImg.onload = function() {
    c++;
    };
    });

var interval = setInterval(function() {
    percent = n/100;
    loaded = c/percent;

    // for displaying purposes
    setBar(getBar()+50)
    // feed loaded var to the progressbar
    if (loaded == 100) {
    clearInterval(interval);
    }

    }, 1);

function setBar(n) {
  var bar = document.getElementById('fabbar');
  bar.style.width = n+'%';
}
function getBar() {
  var bar = document.getElementById('fabbar');
  return parseInt(bar.style.width);
}

</script>

</head>
<body>

<div class="progress progress-info progress-striped active">
<div class="bar" id='fabbar' style="width: 20%"></div>
</div>

但这不起作用,即进度条没有进展。我怎么能那样做?

4

1 回答 1

5

试试这个(演示):

$(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 + '%');
    });
});
于 2013-04-14T03:36:25.163 回答