<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 简单设定一个样式 -->
<style>
*{margin: 0;padding: 0;}
section{
width: 200px;
height: 300px;
background: red;
overflow: hidden;
}
section h1{
width: 200px;
font-size: 30px;
color: white;
text-align: center;
margin-top: 30px;
}
section h3{
width: 200px;
font-size: 20px;
color: white;
text-align: center;
margin-top: 100px;
}
section div{
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
font-size: 30px;
color: white;
}
section div span{
color: white;
display: block;
background: rgba(0,0,0,0.6);
font-size: 30px;
}
</style>
</head>
<body>
<section>
<h1>电商秒杀</h1>
<h3>18:点场 距结束</h3>
<div>
<span>00</span> :
<span>00</span> :
<span>00</span>
</div>
</section>
<script>
// 先将所需要用到的标签对象获取
var oSection = document.querySelector('section');
var oDiv = oSection.querySelector('div');
var oSpan0 = oDiv.querySelectorAll('span')[0];
var oSpan1 = oDiv.querySelectorAll('span')[1];
var oSpan2 = oDiv.querySelectorAll('span')[2];
// 定义变量 时h 分m 秒s
var h = 0;
var m = 0;
var s = 0;
// 封装获取时间差的函数
function getKillTime(time){
// 设定定时器,时间间隔为1秒 作用刷新时间
setInterval(function(){
// 开始时间 为当地时间的时间戳时间
var starTime = (new Date()).getTime();
// 结束时间 为自定义时间的时间戳时间 具体多久结束根据个人需求
var endTime = (new Date(time)).getTime();
// 获取时间戳的差 并将其转化为对应的秒数
var killTime = (endTime - starTime)/1000;
// 计算具体的 时h 分m 秒s
h = parseInt(killTime/(60*60))
m = parseInt((killTime%(60*60))/60)
s = parseInt(killTime%60)
// 将获取的时间 写入到上面咱们写好的 span标签中
// 并对写入的时间进行前导补0操作 优化页面
oSpan0.innerText = h < 10 ? '0' + h : h ;
oSpan1.innerText = m < 10 ? '0' + m : m ;
oSpan2.innerText = s < 10 ? '0' + s : s ;
},1000)
}
getKillTime('2021-8-7 18:0:0')
// @码上成功~
</script>
</body>
</html>