<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#container{
width: 280px;
height: auto;
margin: 0 auto;
border: 1px solid #ccc;
}
#countdown{
background: #eefbff;
font-size: larger;
font-weight: bolder;
text-align: center;
color: chocolate;
line-height: 34px;
height: 70px;
}
#btn{
margin: 10px;
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<div id="countdown">
</div>
<div id="btn">
<button id="seckillBtn" style="width: 80px" disabled>秒杀</button>
</div>
</div>
<script>
//秒杀显示dom节点
let countdownDom = document.getElementById("countdown");
//秒杀活动标题
let itemTitle = "京东3.8节秒杀活动"
//秒杀开始时间
let d = new Date('2024-03-04 22:24:00')
//定时器对象
let timer;
//倒计时函数
function countDown(date) {
let now = new Date()
let ms = date - now;
if(ms<=0){
countdownDom.innerHTML = ('秒杀进行中....')
document.getElementById("seckillBtn").disabled=false;
clearInterval(timer)
return;
}
let day = Math.floor(ms / (1000 * 60 * 60 * 24));
let hour = Math.floor(ms / (1000 * 60 * 60)) - day * 24;
let min = Math.floor(ms / (1000 * 60)) - (day * 24 * 60) - (hour * 60);
let s = Math.floor(ms / 1000) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (min * 60);
countdownDom.innerHTML = ('距离' + itemTitle + '还有<br>' + day + '天' + hour + '小时' + min + '分钟' + s + '秒')
}
timer = setInterval(function () {
countDown(d), 1
})
</script>
</body>
</html>
运行效果
