jquery循环进度条

时间:2015-12-02 08:56:11

标签: javascript jquery html

我需要在循环中运行以下进度条。因此,在计数到零之后,再次使用定义的值重新开始。

http://jsfiddle.net/zessx/4PKEB/1/

这是JS

<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
function progress(timeleft, timetotal, $element) {
    var progressBarWidth = timeleft * $element.width() / timetotal;
    $element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html(timeleft + " seconds to go");
    if(timeleft > 0) {
        setTimeout(function() {
            progress(timeleft - 1, timetotal, $element);
        }, 1000);
    }
};

progress(20, 20, $('#progressBar'));
});//]]> 

</script>

</head>
<body>
  <div id="progressBar">
  <div></div>
</div>

2 个答案:

答案 0 :(得分:1)

if(timeleft > 0) {
        setTimeout(function() {
            progress(timeleft - 1, timetotal, $element);
        }, 1000);
    }
else
    progress(20, 20, $('#progressBar'));

如果timeleft==0,请再次调用该函数。

Fiddle

答案 1 :(得分:1)

如果timeleft为0,则可以重置值并再次调用progress()

function progress(timeleft, $element, timetotal) {
  timetotal = arguments.length == 3 ? timetotal : timeleft;
  var progressBarWidth = timeleft * $element.width() / timetotal;
  $element.find('div').animate({
    width: progressBarWidth
  }, timeleft == timetotal ? 1 : 1000, 'linear', function() {
    progress(timeleft == 0 ? timetotal : timeleft - 1, $element, timetotal);
  }).html(timeleft + " seconds to go");
};

progress(5, $('#progressBar'));
#progressBar {
  width: 90%;
  margin: 10px auto;
  height: 22px;
  background-color: #0A5F44;
}
#progressBar div {
  height: 100%;
  text-align: right;
  padding: 0 10px;
  line-height: 22px;
  /* same as #progressBar height if we want text middle aligned */
  width: 0;
  background-color: #CBEA00;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="progressBar">
  <div></div>
</div>