使用jQuery和CSS的Progressbar

时间:2014-06-25 14:38:57

标签: javascript jquery html css

这是我使用的HTML:

<progress id="amount" value="0" max="100"></progress>

这是我使用的JavaScript:

<script>
for (var i = 0; i < 240; i++) {
    setTimeout(function () { // this is 8 minutes progressbar
        var t = Math.floor((i / 240) * 100);
        $('#amount').attr('value', t);
    }, 2000);
}
</script>

问题是该值在第一秒直接跳到100%。

请帮忙 提前致谢

4 个答案:

答案 0 :(得分:2)

你意识到for每次都会设定你的计时器,是吗?并且它非常快,你甚至无法注意到。 实际上没有必要,你的计时器已经用于循环。删除它。

<script>
     var i = 0;
     var timer = setInterval(function () { // this is 8 minutes progress bar
        if(i<240) { 
            i++;
            var t = Math.floor((i / 240) * 100);
            $('#amount').attr('value', t);
        } else {
            clearInterval(timer);
            timer=null;
        }
    }, 2000);

</script>

答案 1 :(得分:0)

您在开始时设置了所有240个setTimeouts,因此它们都会在页面加载后运行2秒。 (for循环在设置下一个循环之前不会等待每一个循环运行,因为你还没有告诉它)。

尝试类似这样的事情,只有在前一个事件发生后才设置以下setTimeout

var i = 0;

function tick() {
    var t = Math.floor((i / 240) * 100);
    $('#amount').attr('value', t);

    if (i < 240) {
        i++;
        setTimeout(tick, 2000); // set the next progression of the bar for 2 seconds after this one
    }
};

tick(); // do the first progression of the bar

使用JSFiddle:http://jsfiddle.net/xhsP8/2/

答案 2 :(得分:0)

您可以创建一个闭包来执行此操作。两种方式:

for (var i = 0; i < 240; i++) {
    setTimeout(function (x) {
        return function () {
            $('#amount').prop('value', Math.floor((x / 240) * 100));
        }
    }(i), 2000*i);
}

var func = function (i) {
    return function () {
        $('#amount').prop('value', Math.floor((i / 240) * 100));
    }
}
for (var i = 0; i < 240; i++) {
    setTimeout(func(i), 2000 * i);
}

<强> jsFiddle example

答案 3 :(得分:-2)

jquery进度条的api为here可以看到here

的示例

以下是一些示例代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Progressbar - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#progressbar" ).progressbar({
      value: 37
    });
  });
  </script>
</head>
<body>

<div id="progressbar"></div>


</body>
</html>