使用js编写一个时间倒计时代码
时间: 2024-05-16 20:12:22 浏览: 20
好的,下面是一个简单的使用 JavaScript 编写的时间倒计时代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>倒计时示例</title>
</head>
<body>
<div id="countdown"></div>
<script>
// 倒计时的目标时间
var targetTime = new Date("2022-01-01T00:00:00").getTime();
// 每秒更新倒计时显示
setInterval(function() {
// 当前时间
var now = new Date().getTime();
// 倒计时剩余时间(单位:毫秒)
var remainingTime = targetTime - now;
// 计算倒计时剩余天、小时、分钟、秒数
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);
// 更新倒计时显示内容
document.getElementById("countdown").innerHTML = "倒计时:" + days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";
}, 1000);
</script>
</body>
</html>
```
这段代码会在页面上显示一个倒计时,以目标时间 `2022-01-01T00:00:00` 为结束时间,每秒钟更新一次显示。你可以根据需要修改目标时间,以实现不同的倒计时功能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)