gpt4 book ai didi

javascript倒数计时器变为负值

转载 作者:行者123 更新时间:2023-11-28 12:43:24 25 4
gpt4 key购买 nike

我正在尝试使用 javascript 在我的移动网站上实现倒数计时器。我有这个,但计时器变为负数,它不会停止。我希望它在 0:0 停止。

JavaScript

// set minutes
var mins = 5;

// calculate seconds
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}

HTML

<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; font-weight: bold;"> minutes and <input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;"> seconds.
</div>

而且我也在尝试将倒计时分钟的字体颜色更改为红色,但它似乎没有改变?

<input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; **font-color:red;** font-weight: bold;">

最佳答案

  1. 您正在无条件地将 setTimeout 设置为重复。尝试 if( secs > 0) setTimeout(Decrement,1000)

  2. CSS 是color,不是font-color

你的代码也很乱...

var time = 5 * 60,
start = Date.now(),
mins = document.getElementById('minutes'),
secs = document.getElementById('seconds'),
timer;

function countdown() {
var timeleft = Math.max(0, time - (Date.now() - start) / 1000),
m = Math.floor(timeleft / 60),
s = Math.floor(timeleft % 60);

mins.firstChild.nodeValue = m;
secs.firstChild.nodeValue = s;

if( timeleft == 0) clearInterval(timer);
}

timer = setInterval(countdown, 200);
<div id="timer">
This is only valid for the next <strong id="minutes">-</strong> minutes and <strong id="seconds">-</strong> seconds.
</div>

关于javascript倒数计时器变为负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25891561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com