倒计时案例
<!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>
div {
margin: 100px 500px;
}
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: rgb(14, 13, 13);
color: #fff;
font-size: 18px;
text-align: center;
line-height: 50px;
}
</style>
</head>
<body>
<div>
<span class="hour">1</span>
<span class="minute">2</span>
<span class="second">3</span>
</div>
<script>
// 获取元素
var hour = document.querySelector('.hour') // 小时的盒子
var minute = document.querySelector('.minute') // 分钟的盒子
var second = document.querySelector('.second') // 秒速的盒子
var inputTime = +new Date('2022-5-1 18:00:00');// 用户输入的时间总毫秒
countDown()
// 2 开启定时器
setInterval(countDown, 1000)
function countDown() {
var nowTime = +new Date(); // 当前的时间总毫秒
var times = (inputTime - nowTime) / 1000;//剩余总时间的秒数
var h = parseInt(times / 60 / 60 % 24); // 时
h = h < 10 ? '0' + h : h;
hour.innerHTML = h;
var m = parseInt(times / 60 % 60); //分
m = m < 10 ? '0' + m : m;
minute.innerHTML = m;
var s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
second.innerHTML = s;
}
</script>
</body>
</html>