当我选择一个特定的时间时,我试图让我的按钮开始计数。现在,当我点击一个,它只显示时间,它没有开始倒计时。
<html>
<div class="app">
<div class="time-select">
<button data-time="120">2 Minutes</button>
<button data-time="300">5 Minutes</button>
<button data-time="600">10 Minutes</button>
</div>
<div class="timer-container">
<h3 class="time-display">0:00</h3>
</div>
</div>
</html>
const timeDisplay = document.querySelector(".time-display");
const timeSelect = document.querySelectorAll(".time-select button");
let fakeDuration = 600;
timeSelect.forEach(option => {
option.addEventListener("click", function(){
fakeDuration = this.getAttribute("data-time");
timeDisplay.textContent = `${Math.floor(fakeDuration / 60)}:${Math.floor(fakeDuration %
60)}`;
});
});
ontimeUpdate = () => {
let elapsed = fakeDuration;
let seconds = Math.floor(elapsed % 60);
let minutes = Math.floor(elapsed / 60);
timeDisplay.textContent = `${minutes}:${seconds}`;
};发布于 2022-02-02 00:11:09
您需要使用setInterval() --此外,我还修复了您计算分钟和秒的方式。JS使用毫秒-通常最好是标准化时间保持/计数,以适应JS的现有规则。
const timeDisplay = document.querySelector(".time-display");
const timeSelect = document.querySelectorAll(".time-select button");
let fakeDuration, interval
timeSelect.forEach(option => {
option.addEventListener("click", function() {
clearInterval(interval)
fakeDuration = +this.getAttribute("data-time");
interval = setInterval( () => ontimeUpdate(), 1000)
});
});
ontimeUpdate = () => {
fakeDuration -= 1000;
if (fakeDuration <= 0) clearInterval(interval)
let minutes = ('0' + Math.floor(fakeDuration / 60000)).slice(-2);
let seconds = ('0' + (fakeDuration % 60000)/1000).slice(-2);
timeDisplay.textContent = `${minutes}:${seconds}`;
};<div class="app">
<div class="time-select">
<button data-time="120000">2 Minutes</button>
<button data-time="300000">5 Minutes</button>
<button data-time="600000">10 Minutes</button>
</div>
<div class="timer-container">
<h3 class="time-display">0:00</h3>
</div>
</div>
https://stackoverflow.com/questions/70949030
复制相似问题