2014-06-25 33 views
0

這是我使用HTML:進度使用jQuery和CSS

<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%的第一秒。

請幫助 在此先感謝

回答

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> 
+2

+1更好的教程。我正要寫下這個...... –

+0

一切正常工作非常感謝除了進度在96秒內結束我可以使用單一方法8分鐘,但我想如果你能幫助找出問題。 –

+0

@php_to_android你的意思是太快? – nicael

-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> 
+0

這裏存在http://hayageek.com/jquery-progress-bar-example/ –

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/

+0

一切工作非常感謝除了進度在96秒內結束我可以使用單一方法8分鐘,但我想如果你能幫助找出問題。 –

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