javascript倒数计时器变为负数

标签 javascript html css timer

我正在尝试使用 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/

相关文章:

javascript - onPress 事件不适用于 React Native 中的 View 、图像、可触摸不透明度

jquery - 将字段设为只读 - 复选框 - jQuery

html - div没有高度

html - 在没有脚本的情况下创建引用其他文本的 Vanilla 工具提示/弹出窗口

css - 具有多个入口点的 node-sass 脚本

javascript - 如何在原生 JavaScript 中观察 body 元素的类属性变化?

javascript - 选择选择框后加载sql数据?

javascript - Canvas 对象总是绘制在其他对象后面

html - 带有水平形式的长文本的 <label> 不会在输入字段的对面垂直居中

jquery - float DIV