js 倒计时
时间: 2023-07-08 19:08:55 浏览: 57
可以使用 JavaScript 实现倒计时。以下是一个简单的倒计时示例:
HTML 代码:
```html
<p id="countdown"></p>
```
JavaScript 代码:
```javascript
// 设置结束时间,格式为 yyyy-mm-dd hh:mm:ss
var endTime = "2021-12-31 23:59:59";
// 获取倒计时元素
var countdownEl = document.getElementById("countdown");
// 每秒更新倒计时
var countdownInterval = setInterval(function() {
// 计算剩余时间
var remainingTime = new Date(endTime) - new Date();
// 如果剩余时间小于等于 0,停止计时器并显示已结束
if (remainingTime <= 0) {
clearInterval(countdownInterval);
countdownEl.innerText = "已结束";
return;
}
// 计算剩余天数、小时数、分钟数和秒数
var remainingDays = Math.floor(remainingTime / 86400000);
var remainingHours = Math.floor((remainingTime % 86400000) / 3600000);
var remainingMinutes = Math.floor((remainingTime % 3600000) / 60000);
var remainingSeconds = Math.floor((remainingTime % 60000) / 1000);
// 格式化剩余时间并显示
countdownEl.innerText = remainingDays + "天 " + remainingHours + "小时 " + remainingMinutes + "分钟 " + remainingSeconds + "秒";
}, 1000);
```
这个示例会从当前时间开始计算距离指定结束时间的剩余时间,并每秒更新一次倒计时元素的文本内容。如果剩余时间小于等于 0,就会停止计时器并显示已结束。
相关推荐
![](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)