请用js代码编写一个毕业倒计时
时间: 2023-09-03 10:05:52 浏览: 123
以下是一个使用 JavaScript 编写的毕业倒计时的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>毕业倒计时</title>
</head>
<body>
<h1>毕业倒计时</h1>
<p id="countdown"></p>
<script>
// 设置毕业日期(注意:月份从0开始,所以5代表6月)
const graduateDate = new Date(2022, 5, 30);
// 获取现在的时间
function getCurrentTime() {
return new Date().getTime();
}
// 计算距离毕业还有多少天、小时、分钟和秒钟
function calculateCountdown() {
const now = getCurrentTime();
const difference = graduateDate.getTime() - now;
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((difference % (1000 * 60)) / 1000);
return {
days,
hours,
minutes,
seconds
};
}
// 更新倒计时显示
function updateCountdown() {
const countdownElement = document.getElementById('countdown');
const { days, hours, minutes, seconds } = calculateCountdown();
countdownElement.innerHTML = `距离毕业还有 ${days} 天 ${hours} 小时 ${minutes} 分钟 ${seconds} 秒`;
}
// 每秒钟更新一次倒计时显示
setInterval(updateCountdown, 1000);
</script>
</body>
</html>
```
该代码首先定义了毕业日期(在示例代码中是2022年6月30日),然后编写了三个函数:
- `getCurrentTime`:获取现在的时间(以毫秒为单位)。
- `calculateCountdown`:计算距离毕业还有多少天、小时、分钟和秒钟。
- `updateCountdown`:根据 `calculateCountdown` 函数的返回值,更新倒计时显示。
最后,通过 `setInterval` 函数,每秒钟调用一次 `updateCountdown` 函数,从而实现倒计时的动态更新。