js实现距离2023年5月1日还有多少天,小时,分,秒的实时倒计时效果?

如题所述

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>倒计时</title>
</head>
<body>
<div id="countdown"></div>
<script>
// 定义倒计时截止时间
const endTime = new Date('2023-05-01 00:00:00').getTime();
// 每秒更新一次倒计时
const countdown = setInterval(function() {
// 获取当前时间戳
const nowTime = new Date().getTime();
// 计算时间差(毫秒)
const timeDiff = endTime - nowTime;
// 计算剩余天数、小时数、分钟数、秒数
const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
// 将倒计时显示在页面上
document.getElementById('countdown').innerHTML = '距离2023年5月1日还有:' + days + '天 ' + hours + '小时 ' + minutes + '分 ' + seconds + '秒';
// 结束倒计时
if (timeDiff < 0) {
clearInterval(countdown);
document.getElementById('countdown').innerHTML = '倒计时已结束!';
}
}, 1000);
</script>
</body>
</html>
温馨提示:答案为网友推荐,仅供参考
相似回答