效果图:
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
h1{
font-size:60px;
text-align:center;
margin:80px auto;
line-height: 200px;
color:orange;
}
</style>
</head>
<body>
<div id="box">
<h1>距离2020年元旦还剩</h1>
<h1 class="last">00年00月00日 00时00分00秒000毫秒</h1>
</div>
<script>
var h1=document.querySelector(".last");
setInterval(function(){
var d=+new Date("2020-1-1 0:0:0");
var b=+new Date();
//通过方法获取年 月 日 小时 分钟 秒 毫秒值
var year=parseInt((d-b)/1000/60/60/24/365);
var month=parseInt((d-b)/1000/60/60/24/30%12);
var date=parseInt((d-b)/1000/60/60/24%30);
var hour=parseInt((d-b)/1000/60/60%24);
var mintue=parseInt((d-b)/1000/60%60);
var second=parseInt((d-b)/1000%60);
var ms=parseInt((d-b)%1000);
year=year<10?"0"+year:year;
month=month<10?"0"+month:month;
date=date<10?"0"+date:date;
hour=hour<10?"0"+hour:hour;
//三目运算判断分钟和秒的长度
mintue=mintue<10?"0"+mintue:mintue;
second=second<10?"0"+second:second;
//判断毫秒值的长度
if(ms<10){
ms="00"+ms
}else if(ms<100){
ms="0"+ms
}
var str=year+"年"+month+"月"+date+"日 "+hour+"时"+mintue+"分"+second+"秒"+ms+"毫秒";
h1.innerHTML=str;
},1)
</script>
</body>
</html>