【问题标题】:Showing a time countdown progress bar显示时间倒计时进度条
【发布时间】:2020-05-04 19:03:49
【问题描述】:

我在this site 上看到了这个进度条码。

我想做的是,倒计时 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

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

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;
}

【问题讨论】:

  • 百分比是可以的,我想可视化。但文字必须显示还剩多少时间。

标签: jquery css


【解决方案1】:

你需要稍微改变一下这个函数:

  • 使用 3 个参数(timeleft、timetotal、element)而不是 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;
}

片段:

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'));
#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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="progressBar">
  <div></div>
</div>

[提示]

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

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

【讨论】:

  • 所以这使它从 100% 宽度下降到 0%,如果我想反过来,从 0 到 100 怎么办?
  • 去吧,它是“var progressBarWidth = (timetotal-timeleft) * ($element.width()/timetotal);”
  • 嗨@zessx,如何在页面加载时禁用进度条动画?
猜你喜欢
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多