用JavaScript写一个倒计时
时间: 2024-05-15 14:20:00 浏览: 25
可以使用JavaScript的Date对象和定时器函数setInterval来实现一个简单的倒计时。
HTML部分:
```html
<div id="countdown"></div>
```
JavaScript部分:
```javascript
// 目标日期,格式为"年-月-日 时:分:秒"
var targetDate = "2021-12-31 23:59:59";
// 获取目标日期的时间戳
var targetTime = new Date(targetDate).getTime();
// 定义定时器函数
var timer = setInterval(function() {
// 获取当前时间的时间戳
var nowTime = new Date().getTime();
// 计算剩余时间的毫秒数
var remainingTime = targetTime - nowTime;
// 如果剩余时间小于等于0,停止定时器
if (remainingTime <= 0) {
clearInterval(timer);
document.getElementById("countdown").innerHTML = "倒计时已结束";
return;
}
// 将毫秒数转换为天、小时、分钟、秒
var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
// 将倒计时显示在页面上
var countdownStr = "倒计时:" + days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
document.getElementById("countdown").innerHTML = countdownStr;
}, 1000);
```
上面的代码中,首先定义了目标日期和目标日期的时间戳。然后使用setInterval函数每隔1秒执行一次定时器函数。在定时器函数中,首先获取当前时间的时间戳,然后计算剩余时间的毫秒数。如果剩余时间小于等于0,说明倒计时已结束,停止定时器并在页面上显示相应信息。否则,将剩余时间转换为天、小时、分钟、秒,然后将倒计时显示在页面上。
相关推荐
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)