<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box3{
width: 100px;
height: 100px;
background-color: black;
text-align: center;
font-size: 80px;
color: white;
}
</style>
</head>
<body>
<div>当前时间是:<span id="box"></span></div>
<div>距离毕业倒计时:<span id="box2"></span></div>
<script>
let box = document.getElementById("box");
function timer() {
let myDate = new Date();
let s = `
${myDate.getFullYear()}年
${myDate.getMonth()+1}月
${myDate.getDate()}日
${myDate.getHours()}:
${myDate.getMinutes()}:
${myDate.getSeconds()}
`
box.innerHTML = s;
}
setInterval(timer, 1000);
</script>
<script>
let box2 =document.getElementById("box2");
const targetDate = new Date('2025-06-30T00:00:00').getTime();
function updateCountdown() {
const currentDate = new Date().getTime();
const difference = targetDate - currentDate;
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);
document.getElementById('box2').innerHTML = `
${days} 天
${hours} 小时
${minutes} 分钟
${seconds} 秒
`;
}
updateCountdown();
setInterval(updateCountdown, 1000);
</script>
<div class="box3" id="01"></div>
<script>
let seconds = 5;
const countdownElement = document.getElementById('01');
function countdown() {
countdownElement.innerHTML = seconds;
seconds--;
if (seconds >= 0) {
setTimeout(countdown, 1000);
} else {
seconds = 5;
setTimeout(countdown, 1000);
}
}
countdown();
</script>
</body>
</html>
运行结果
本次练习中实现了三种效果,记录当前时间,对某一时刻的倒计时,以及一个循环5s的倒计时效果,我在本此练习中,注意到的细节有,
getMonth()是从0开始的,为此要显示正确月份,需要再加个1。
在制作对某一日期倒计时,日期的写法有两种
(1)"2024/05/06 12:12:12" (2)"2024-05-06 12:12:12"