<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>倒计时</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: lightcyan;
}
#time {
width: 500px;
height: 80px;
line-height: 80px;
border: 1px dashed darkblue;
margin: 0 auto;
text-align: center;
font-size: 24px;
}
</style>
</head>
<body>
<div id="time">06时45分30秒</div>
</body>
</html>
<script>
/*
现在的时间:
目标时间:"2020-11-20 17:00:00"
时间差:new Date('2020-11-20 17:00:00')-new Date()
*/
function timedown(str){
var times = new Date(str) - new Date();
if(times<=0){
clearInterval(timer);
timer=null;
return 'timepass';
}
var hours = Math.floor(times / 1000 / 60 / 60);
var min = Math.floor((times-hours*1000*60*60)/1000/60);
var sec = Math.floor((times-hours*1000*60*60-min*1000*60)/1000);
return fn(hours)+'时'+fn(min)+'分'+fn(sec)+'秒'
}
function fn(num){
if(num<10){
return '0'+num
}
return num;
}
//目标时间
var str='2020-11-20 17:00:00';
document.getElementById('time').innerText =timedown(str)
var timer=setInterval(function () {
document.getElementById('time').innerText =timedown(str)
}, 1000)
</script>