【发布时间】:2019-01-23 22:10:11
【问题描述】:
我有两个 Date() 时间,我试图使用它们之间的差异来设置进度条的宽度,当时间之间没有更多差异时,它会从 100% 缩小到 0%,但我得到了非常奇怪的结果。
这就是我目前正在尝试的方式(它在 React 中被拆分为几个不同的函数,所以我只包含相关的代码):
首先,我设置了目标日期时间,将endDate 设置为接下来 24 小时内(例如晚上 10 点)的最开始...
this.endDate = new Date();
if (this.props.data.end_hr === 0) {
this.endDate.setHours(24, 0, 0, 0);
} else {
this.endDate.setHours(this.props.data.end_hr);
}
this.endDate.setMinutes(0);
this.endDate.setSeconds(0);
this.countdown = setInterval(this.timeRemaining, 1000);
然后在每秒触发的timeRemaining 函数中,我获取当前日期时间并计算它们之间的差异。最后,我正在尝试计算发送到进度条 CSS 宽度属性的百分比...
let now = new Date().getTime();
let diff = this.endDate - now;
let percent =
Math.round(((diff / this.endDate) * 100000000 * 2) / 100) + '%';
this.countdownProgress.style.width = percent;
diff 100% 正确,但百分比错误。
我已经尝试了各种不同的方法来计算我能想到的百分比,但没有任何效果,上面的方法是我能得到的最接近的方法。
谁能告诉我哪里出错了?
编辑:@Danziger 的回答以我想使用的方式实现。这将开始时间设置为晚上 10 点,结束时间设置为午夜。
事实证明它确实可以正常工作,所以我的代码中肯定有其他东西导致了这个问题。再次感谢 Danziger 让我看到光明!
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
const startDate = new Date();
startDate.setHours(22);
startDate.setMinutes(0);
startDate.setSeconds(0);
const endDate = new Date();
endDate.setHours(24,0,0,0);
endDate.setMinutes(0);
endDate.setSeconds(0);
const range = endDate - startDate;
function updateCountdown() {
const diff = Math.max(0, endDate - new Date());
progressBar.style.width = `${ 100 * diff / range }%`;
progressText.innerText = `${ `000${ Math.ceil(diff / 1000) }`.slice(-4) } seconds`
if (diff >= 0) {
requestAnimationFrame(updateCountdown);
}
}
updateCountdown();
body {
font-family: monospace;
}
.progressBar__base {
position: relative;
height: 32px;
border: 3px solid black;
margin: 0 0 8px;
}
.progressBar__progress {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: blue;
}
<div class="progressBar__base">
<div class="progressBar__progress" id="progressBar"></div>
</div>
<div id="progressText"></div>
【问题讨论】:
-
当您要计算
diff / (endDate - startDate)时,您正在计算diff / endDate- 即diff占startDate和endDate之间总时间的百分比。此外,使用您当前对diff的定义将为您提供一个递减 进度条。如果您想要增加,请改用diff = now - startDate。 -
刚刚尝试过 -
Math.round(diff / (this.endDate - now))并且我收到了1回复?有问题的 endDate 目前设置为英国午夜,目前是 22:29。 -
啊,所以我需要提供开始日期?我不这样做。只有 endDate 和当前时间
-
如果没有开始日期,就无法知道已经取得了多少进展。这就像在问“鉴于您已经旅行了 200 英里,您到多伦多的旅程已经完成了多少?”
-
我们都去过那里:p
标签: javascript percentage