最近做项目需要用到一个倒时器的功能,于是用JS做了一个简易的倒计时原理。
//js核心模块
<script type="text/javascript">
function countDown(){
//获取当前的时间
var nowTime=new Date();
//获取倒计时结束时间
var endTime=new Date('2018/06/30 12:00:00');
//获取剩余的时间(以毫秒为单位)
var remianSecond=(endTime.getTime()-nowTime.getTime())/1000;
//换算成天
var d=Math.floor(remianSecond/60/60/24);
//换算成时
var h=Math.floor(remianSecond/60/60%24);
//换算成分
var m=Math.floor(remianSecond/60%60);
//换算成秒
var s=Math.floor(remianSecond%60);
if(d<10){
d="0"+d;
}
if(h<10){
h="0"+h;
}
if(m<10){
m="0"+m;
}
if(s<10){
s="0"+s;
}
document.getElementById("d").innerHTML=d+"天";
document.getElementById("h").innerHTML=h+"时";
document.getElementById("m").innerHTML=m+"分";
document.getElementById("s").innerHTML=s+"秒";
}
setInterval(countDown,0)
</script>
//html代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>js简易倒时器</title>
<style>
*{margin:0; padding:0; list-style:none;}
body{font-size:18px; text-align: center;}
.time{height:30px; padding:200px;}
</style>
</head>
<body>
<div class="time">
<span id="d">00天</span>
<span id="h">00时</span>
<span id="m">00分</span>
<span id="s">00秒</span>
</div>
</body>
</html>

解读原理后,就可以以不变应万变了!!
网友评论