使用js生成简易倒计时
时间: 2023-12-02 09:05:18 浏览: 22
好的,以下是使用 JavaScript 生成简易倒计时的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>简易倒计时</title>
</head>
<body>
<div id="countdown"></div>
<script>
// 设置倒计时结束时间,这里是2022年1月1日0时0分0秒
var countdownDate = new Date("Jan 1, 2022 00:00:00").getTime();
// 每秒更新倒计时
var countdownInterval = setInterval(function() {
// 获取当前时间
var now = new Date().getTime();
// 计算距离倒计时结束的时间
var distance = countdownDate - now;
// 计算剩余时间的天、小时、分钟和秒
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// 在页面上显示剩余时间
document.getElementById("countdown").innerHTML = "距离2022年1月1日还有:" + days + "天 " + hours + "小时 "
+ minutes + "分钟 " + seconds + "秒";
// 如果倒计时结束,清除定时器
if (distance < 0) {
clearInterval(countdownInterval);
document.getElementById("countdown").innerHTML = "倒计时已结束!";
}
}, 1000);
</script>
</body>
</html>
```
这段代码会在页面上显示距离2022年1月1日的倒计时,并且每秒钟更新一次。你可以根据自己的需要修改倒计时结束时间和页面上显示的文本。