第一种
思路
1.通过得出现在的时间距离终点时间得出毫秒
2.毫秒转秒
3.通过秒得出小时,分钟,秒不断更新
<!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>
box2{
width: 200px;
height: 100px;
margin: 0 auto;
color: black ;
font-size: 20px;
}
.time2{
color: rgb(255, 255, 255);
background-color: crimson;
border: 3px solid crimson;
}
</style>
</head>
<body>
<div class="box2">
<span class="time2 hour2">12</span>
<span>:</span>
<span class="time2 minute2">30</span>
<span>:</span>
<span class="time2 second2">30</span>
</div>
</body>
<script>
function padLeft(content,count,str)
{
count = count || 2;
str =str || "0"
content = String(content)
return content.padStart(count,str);
}
var hourEl2 =document.querySelector(".hour2");
var minuteEl2 =document.querySelector(".minute2");
var secondEl2 =document.querySelector(".second2");
var endTime = new Date();
endTime.setHours(24);
endTime.setMinutes(0);
endTime.setSeconds(0);
setInterval(
function()
{
var date =new Date();
var miao = parseInt((endTime - date)/1000);
var hour1 =padLeft (parseInt(miao/3600));
var minute1 =padLeft (parseInt(miao/60%60));
var second1 =padLeft (parseInt(miao%60));
hourEl2.textContent = hour1;
minuteEl2.textContent = minute1;
secondEl2.textContent = second1;
},1000
)
</script>
</html>
第二种
对位相减
<!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>
.box{
width: 200px;
height: 100px;
margin: 0 auto;
color: black ;
font-size: 20px;
}
.time{
color: rgb(255, 255, 255);
background-color: crimson;
border: 3px solid crimson;
}
</style>
</head>
<body>
<div class="box">
<span class="time hour">12</span>
<span>:</span>
<span class="time minute">30</span>
<span>:</span>
<span class="time second">30</span>
</div>
</body>
<script>
function padLeft(content,count,str)
{
count = count || 2;
str =str || "0"
content = String(content)
return content.padStart(count,str);
}
var hourEl =document.querySelector(".hour");
var minuteEl =document.querySelector(".minute");
var secondEl =document.querySelector(".second");
setInterval(
function()
{
var date =new Date();
var hour =padLeft(23 - date.getHours()) ;
var minute =padLeft(59 - date.getMinutes()) ;
var second =padLeft(59 - date.getSeconds()) ;
hourEl.textContent = hour;
minuteEl.textContent = minute;
secondEl.textContent = second;
},1000
)
</script>
</html>