先看效果
上代码
下面展示一些 内联代码片
。
// html
<div>
<span class="hour">1</span>
<span class="minute">2</span>
<span class="second">3</span>
</div>
// css
<style>
div {
margin: 200px;
}
span {
display: inline-block;
width: 40px;
height: 40px;
background-color: #333;
font-size: 20px;
color: #fff;
text-align: center;
line-height: 40px;
}
</style>
// javascript
var hour = document.querySelector(".hour");
var minute = document.querySelector(".minute");
var second = document.querySelector(".second");
var inputTime = +new Date("2020-6-16 20: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; //如果小10 则在前面加0
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 ;
}