<! DOCTYPE html >
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< title> 倒计时示例</ title>
< style>
#countdown {
font-size : 24px;
}
#countdown span {
margin-right : 10px;
}
</ style>
</ head>
< body>
< div id = " countdown" >
距离到期还有:< span id = " days" > 0</ span> 天 < span id = " hours" > 0</ span> 小时 < span id = " minutes" > 0</ span> 分钟 < span id = " seconds" > 0</ span> 秒
</ div>
< script>
const expiryDate = new Date ( 2024 , 3 , 2 ) ;
function updateCountdown ( ) {
const now = new Date ( ) ;
const diff = expiryDate - now;
if ( diff < 0 ) {
clearInterval ( intervalId) ;
document. getElementById ( 'countdown' ) . textContent = '已到期' ;
return ;
}
const diffDays = Math. floor ( diff / ( 1000 * 60 * 60 * 24 ) ) ;
const diffHours = Math. floor ( ( diff % ( 1000 * 60 * 60 * 24 ) ) / ( 1000 * 60 * 60 ) ) ;
const diffMinutes = Math. floor ( ( diff % ( 1000 * 60 * 60 ) ) / ( 1000 * 60 ) ) ;
const diffSeconds = Math. floor ( ( diff % ( 1000 * 60 ) ) / 1000 ) ;
document. getElementById ( 'days' ) . textContent = diffDays;
document. getElementById ( 'hours' ) . textContent = diffHours;
document. getElementById ( 'minutes' ) . textContent = diffMinutes;
document. getElementById ( 'seconds' ) . textContent = diffSeconds;
}
updateCountdown ( ) ;
const intervalId = setInterval ( updateCountdown, 1000 ) ;
</ script>
</ body>
</ html>