样图展示
html模块
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>距离双12倒计时</title>
<link rel="stylesheet" href="css/ms.css">
</head>
<body>
<div class="countdown">
<h2>秒杀时间</h2>
<p id="targetTime">2022-12-12 0:0:0</p>
<div class="show">
<div class="day">
<div class="number">10</div>
<span class="text">天</span>
</div>
<div class="day">
<div class="number">06</div>
<span class="text">小时</span>
</div>
<div class="day">
<div class="number">16</div>
<span class="text">分</span>
</div>
<div class="day">
<div class="number">51</div>
<span class="text">秒</span>
</div>
</div>
</div>
<script src="js/ms.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
css模块
.countdown{
display: flex;
flex-direction: column;
justify-content: space-around;
border: 1px solid #000;
margin: 0 auto;
text-align: center;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ),url(../img/bg.jpg)no-repeat center center;
background-size: 100% 220%;
overflow: hidden;
color:#fff;
font-size: 24px;
padding-top: 20px;
}
.show{
display: flex;
justify-content: space-between;
box-sizing: border-box;
padding: 20px 30% 50px;
}
.day{
display: flex;
align-items: center;
}
.day .number{
font-size: 30px;
}
.day .text{
font-size: 15px;
padding-left: 10px;
}
js模块
window.onload = function(){
function calcTime(){
let future = document.getElementById('targetTime').innerHTML;
future = new Date('2022/12/12 00:00:00');
let now = new Date()
console.log(future)
console.log(now)
let diff = Math.ceil((future.getTime() - now.getTime()) / 1000);
return diff;
}
let timer = setInterval(function(){
function showTime(s){
let days = Math.floor(s / 24 / 60 / 60)
let hours = Math.floor(s / 60 / 60) % 24
let minutes = Math.floor(s / 60) % 60
let seconds = s % 60
days = format(days)
hours = format(hours)
minutes = format(minutes)
seconds = format(seconds)
document.querySelector('.show').innerHTML = `<div class="show">
<div class="day">
<div class="number">${days}</div>
<span class="text">天</span>
</div>
<div class="day">
<div class="number">${hours}</div>
<span class="text">小时</span>
</div>
<div class="day">
<div class="number">${minutes}</div>
<span class="text">分</span>
</div>
<div class="day">
<div class="number">${seconds}</div>
<span class="text">秒</span>
</div>
</div>`;
if (s == 0){
document.querySelector('.show').innerHTML = `<h1> 开始抢购!</h1>`;
clearInterval(timer)
}
}
function format(t){
if (t < 10){
t = '0' + t;
} else {
t = t.toString();
}
return t
}
showTime(calcTime());
}, 1000)
}