效果图:
1.先建立两个盒子
<div class="div">
<div class="box"> </div>
</div>
2.给盒子与标签设置相关的css样式
<style>
.div {
width: 500px;
height: 500px;
background-color: rgb(112, 8, 8);
text-align: center;
color: #fff;
position: relative;
}
.box {
width: 305px;
height: 380px;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
p {
margin: auto;
width: 300px;
height: 100px;
line-height: 100px;
font-weight: 700;
font-size: 60px;
background-color: #000;
margin-bottom: 20px;
text-shadow: 3px 5px rgb(112, 8, 8);
}
span {
padding: 5px;
margin: 5px 5px 15px 5px;
display: inline-block;
height: 50px;
width: 50px;
color: rgb(112, 8, 8);
font-size: 30px;
line-height: 50px;
background-color: #fff;
}
</style>
3.JavaScript实现相关的内容
<script>
function time() {
let now = +new Date()
let off = +new Date('2021-10-14 00:00:00')
off = off + 1314 * 60 * 60 * 24 * 1000
// 最时间差
let times = off - now;
// 获取今天的时间
let dt = new Date();
// 获取年月日,时分秒
let year = dt.getFullYear();
let M = dt.getMonth() + 1;
M = M < 10 ? '0' + M : M
let day = dt.getDate();
day = day < 10 ? '0' + day : day
// 将时间戳转换为毫秒
times = times / 1000;
// 计算天数
let d = parseInt(times / 60 / 60 / 24);
// 计算小时
let h = parseInt(times / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
// 计算分数
let m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
// 计算当前秒数
let s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
let div = document.querySelector('.box');
div.innerHTML = `
<h1>距离1314天还有</h1>
<p>${d}天</p>
<span>${h}</span>小时
<span>${m}</span>分钟
<span>${s}</span>秒
今天是: ${year}年${M}月${day}号
`;
// 当倒计时为0天0时0分0秒时,停止计时
if (d == 0 && s == 0 && m == 0 && h == 0) {
clearInterval(timeID)
}
}
// 调用函数
time();
// 开启定时器
let timeID = setInterval(function () {
time();
}, 1000)
</script>