效果如图:
具体代码如下:
<!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;
}
#count {
width: 800px;
height: 200px;
background-color: #3885f9;
margin: 100px auto;
text-align: center;
line-height: 200px;
font-size: 24px;
}
#count span {
width: 60px;
height: 60px;
background: rgba(255, 255, 255, 0.2);
line-height: 60px;
display: inline-block;
vertical-align: middle;
box-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
border-radius: 5px;
}
</style>
</head>
<body>
<div id="count">
距离下班还有:
<span class="day">00</span>
天
<span class="hour">00</span>
小时
<span class="min">00</span>
分钟
<span class="sec"></span>
秒
</div>
</body>
<script>
// 时间对象:
// 未来的时间-现在的时间
var oCount = document.getElementById('count');
var spans = oCount.getElementsByTagName('span');
var endTime = new Date('2022/10/01 23:20:00'); //未来时间
var timer = null;
clearInterval(timer);
timer = setInterval(countTime, 1000);
function countTime() {
var nowTime = new Date(); //现在时间
var lastTime = parseInt((endTime - nowTime) / 1000);
if (lastTime >= 0) {
var day = parseInt(lastTime / 60 / 60 / 24);
var hour = parseInt(lastTime / 60 / 60 % 24);
var min = parseInt(lastTime / 60 % 60);
var sec = parseInt(lastTime % 60);
spans[0].innerHTML = day;
spans[1].innerHTML = hour;
spans[2].innerHTML = min;
spans[3].innerHTML = sec;
} else {
clearInterval(timer);
}
}
</script>
</html>