用js写,已知起止时间,写一个倒计时
时间: 2024-05-15 13:16:05 浏览: 14
以下是用JavaScript编写的倒计时代码。在HTML中,您需要添加一个带有id的元素来显示倒计时。在这个例子中,我使用一个带有"id = countdown"的div元素:
```html
<div id="countdown"></div>
```
在JavaScript中,我们首先获取开始和结束时间的时间戳,然后计算它们之间的时间差。然后,我们使用setInterval函数来每秒更新倒计时,直到时间差为0。
```javascript
// 获取开始和结束时间的时间戳
const startTime = new Date("2021-12-31T23:59:59").getTime();
const endTime = new Date("2022-01-01T00:00:00").getTime();
// 计算时间差
let timeDiff = endTime - startTime;
// 获取显示倒计时的元素
const countdown = document.getElementById("countdown");
// 更新倒计时
const interval = setInterval(() => {
// 计算剩余的天数、小时数、分钟数和秒数
const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
// 更新显示倒计时的元素
countdown.innerHTML = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
// 减少时间差
timeDiff -= 1000;
// 如果时间差为0,停止倒计时
if (timeDiff < 0) {
clearInterval(interval);
countdown.innerHTML = "时间到!";
}
}, 1000);
```