【JS】實現倒計時
阿新 • • 發佈:2020-12-09
技術標籤:javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>時分秒倒計時</title>
<style>
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #333;
margin-right: 5px;
color: #fff;
line-height: 50px;
text-align: center;
}
</style>
</head>
<body>
< span class="hour">1</span>
<span class="min">2</span>
<span class="sencond">3</span>
<script>
var hour = document.querySelector('.hour');
var min = document.querySelector('.min');
var sen = document. querySelector('.sencond');
var inputime = +new Date('2020-12-8 00:08:08');//引數代表使用者輸入日期,返回使用者輸入日期的時間戳(距離1970年的毫秒數)
countdown();//先呼叫一次函式,防止重新整理後出現空白
window.setInterval(countdown, 1000);
function countdown() {
var nowtime = +new Date();
var time = (inputime - nowtime) / 1000;
var h = parseInt(time / 60 / 60 );
var h = h < 10 ? '0' + h : h;
hour.innerHTML = h;
var m = parseInt( time / 60 % 60 );
var m = m < 10 ? '0' + m : m;
min.innerHTML = m;
var s = parseInt( time % 60 );
var s = s <10 ? '0' + s : s;
sen.innerHTML = s;
return '剩餘' + h + '時' + m + '分' + s + '秒';
}
</script>
</body>
</html>