效果:
思路:
先执行一次countDown的原因是网页刷新的时候,setInterval会等待一秒才执行callback函数,还没执行函数之前就会显示出写si的123数字,所以先执行一次countDown函数,用于在刷新网页的时候不会看到写si的数字。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
margin: 100px auto;
}
span{
display: inline-block;
background-color: black;
width: 40px;
height: 40px;
font-size: 20px;
color: #fff;
line-height: 40px;
text-align: center;
}
</style>
</head>
<body>
<div>
<span class="hour">1</span>
<span class="min">2</span>
<span class="sed">3</span>
</div>
</body>
<script>
var hour=document.querySelector('.hour');
var min=document.querySelector('.min');
var sed=document.querySelector('.sed');
var inputTime=+new Date('2022-5-1 18:00:00');
countDown();
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;
min.innerHTML=m;
var s=parseInt(times % 60);
s=s<10?'0'+s:s;
sed.innerHTML=s;
}
</script>
</html>
|