显示时间倒计时进度条

我在这个网站上看到了这个进度条形码。

我想做的是,倒计时3分钟,并显示剩下多少分钟和秒。 因此,而不是显示百分比,我想显示剩余时间。

我使用以下代码:

JS

progress(100, $('#progressBar')); // This is what the timer should update each second function progress(percent, $element) { var progressBarWidth = percent * $element.width() / 100; $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + " minutes/seconds to go"); }; 

HTML

 

CSS

  #progressBar { width: 923px; 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; } 

你需要改变一下这个function:

  • 使用3个参数( timelefttimetotalelement )而不是2个实际参数
  • 使用setTimeout()每秒刷新进度条
  • 检查timeleft以了解是否需要刷新进度条
 function progress(timeleft, timetotal, $element) { var progressBarWidth = timeleft * $element.width() / timetotal; $element .find('div') .animate({ width: progressBarWidth }, 500) .html(timeleft + " seconds to go"); if(timeleft > 0) { setTimeout(function() { progress(timeleft - 1, timetotal, $element); }, 1000); } }; progress(180, 180, $('#progressBar')); 

另外,您应该添加此CSS,以避免进度条溢出其容器:

 #progressBar div { box-sizing: border-box; } 

的jsfiddle

[小费]

如果您希望进度条平滑且不断减少,请改用以下代码:

 .animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, "linear") 

的jsfiddle