我刚开始使用js而且我不知道为什么它不倒计时。有小费吗? (当我使用setInterval
)时它也不起作用。
当eventDate是一种任何通常的日期,如
var eventDate =new date (2016,12,25);
它有效。 控制台没有显示任何错误。
function countdown() {
var now = Date.parse(new Date);
var eventDate = new Date(now + 1800000);
var remTime = eventDate - now;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
m %= 60;
s %= 60;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
setTimeout("countdown()", 1000);
}
countdown();
body {
background: #f6f6f6;
}
.countdownContainer {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
text-align: center;
background: #ddd;
border: 1px solid #ddd;
padding: 10px;
box-shadow: 0 0 5px 3px #ccc;
}
.info {
font-size: 80px;
}
<!DOCTYPE html>
<html>
<head>
<title>Christmas Countdown</title>
</head>
<body>
<table class="countdownContainer">
<tr class="info">
<td colspan="4">Christmas Countdown</td>
</tr>
<tr class="info">
<td id="minutes">12</td>
<td id="seconds">22</td>
</tr>
<tr>
<td>Minutes</td>
<td>Seconds</td>
</tr>
</table>
</body>
</html>
答案 0 :(得分:0)
这里有一些错误,一个是代码,第二个是函数的逻辑。
首先,您需要在setTimeout中传递函数,因此它应该是setTimeout(countdown, 100);
其次在你正在计算的逻辑中
var now = Date.parse(new Date);
var eventDate = new Date(now + 1800000);
然后计算两者的参数,这将导致每个循环的值相同。
var eventDate = new Date(Date.parse(new Date) + 1800000);
function countdown() {
var now = Date.parse(new Date);
var remTime = eventDate - now;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
m %= 60;
s %= 60;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("minutes").innerHTML = m;
document.getElementById("seconds").innerHTML = s;
setTimeout(countdown, 1000);
}
countdown();
&#13;
body {
background: #f6f6f6;
}
.countdownContainer {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
text-align: center;
background: #ddd;
border: 1px solid #ddd;
padding: 10px;
box-shadow: 0 0 5px 3px #ccc;
}
.info {
font-size: 80px;
}
&#13;
<table class="countdownContainer">
<tr class="info">
<td colspan="4">Christmas Countdown</td>
</tr>
<tr class="info">
<td id="minutes">12</td>
<td id="seconds">22</td>
</tr>
<tr>
<td>Minutes</td>
<td>Seconds</td>
</tr>
</table>
&#13;