史上最容易理解的秒杀倒计时
这里以京东秒杀为列,各位看官结合自己的代码看看内容是否可以帮助您
废话不多说直接上图
css部分
* {
margin: 0 auto;
padding: 0;
}
.box {
width: 400px;
height: 600px;
background-color: #ccc;
text-align: center
}
.box h2 {
padding: 60px;
color: red;
font-size: 56px;
}
.box img {
margin-top: 20px;
margin-bottom: 80px;
}
.box h3 {
color: red;
font-size: 28px;
margin-bottom: 20px;
}
.box span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #000;
margin: 0 15px;
color: red;
text-align: center;
line-height: 50px;
font-size: 36px;
font-weight: bold;
}
Html
<div class="box">
<h2>京东秒杀</h2>
<img src="./leidian.png" alt="">
<h3>22:00点场 距结束</h3>
<div class="time">
<span class="h">00</span>
<span class="m">00</span>
<span class="s">00</span>
</div>
</div>
Js部分
// 获取元素
let hour = document.querySelector('.h')
let mou = document.querySelector('.m')
let sec = document.querySelector('.s')
// 处理时间
function countDown(time) {
// 开始时间
let startime = new Date(time)
// 现在时间
let nowtime = new Date();
// 时间差
timer = (startime - nowtime) / 1000
// 1天等于24小时,1小时等于60分钟,1分钟等于60秒,
// 所以请理解下面的表达式(要是真的不理解,请叫自己 “嗦嗨”)
// 补零
let h = parseInt(timer / 3600 % 24)
h = h >= 10? h : '0'+h
let m = parseInt(timer / 60 % 60)
m = m >= 10? m : '0'+m
let s = parseInt(timer % 60)
s = s >= 10? s : '0'+s
// 更新页面元素中的内容——设置时间
hour.innerText = h
mou.innerText = m
sec.innerText = s
}
// 调用函数,这个时间可以自己定义写成xxxx-xx-xx空格xx:xx:xx就行了
setInterval(function(){countDown('2021-12-20 22:00:00')},1000)
定义写成xxxx-xx-xx空格xx:xx:xx就行了
setInterval(function(){countDown(‘2021-12-20 22:00:00’)},1000)