目标:javascript 实现倒计时
步骤:
1.获取目前时间并转换为毫秒数;
2.获取目标时间并转换为毫秒数;
3.获取目前时间与目标时间相差的毫秒数并转换为倒计时显示的天数、时、分、秒;
<!DOCTYPE html>
<html lang="zh-cmn-hans">
<head>
<meta charset="UTF-8">
<title>倒计时</title>
<style>
body, p {
margin: 0;
padding: 0;
}
#time-box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 800px;
height: 100px;
background-color: #e40900;
color: #fff;
font-family: 微软雅黑;
font-size: 30px;
line-height: 100px;
text-align: center;
margin: auto;
}
</style>
</head>
<body>
<p id="time-box"></p>
<script>
function countDown(y,m,d,h,min,s){
var time_box = document.getElementById("time-box"); //获取相应DOM节点
var time_now = new Date().getTime(); //获取1970至今的毫秒数
var time_target_str = y + "/" + m + "/" + d + " " + h + ":" + min + ":" + s; //将目标时间参数转换为字符串
var time_target = Date.parse(time_target_str); //获取1970至目标时间的毫秒数
var time_cut = time_target - time_now; //获取目标时间与目前时间相差的毫秒数
if (time_cut >= 0){
time_box.innerHTML = "距离2018年春节还有:" + Math.floor(time_cut/1000/60/60/24) + "天" + Math.floor(time_cut/1000/60/60%24) + "小时" + Math.floor(time_cut/1000/60%60) + "分" + Math.floor(time_cut/1000%60) + "秒"; //获取倒计时时间
}else{
time_box.innerHTML = "时光如白驹过隙,转瞬即逝!";
}
}
window.onload = setInterval("countDown(2018,2,16,0,0,0)",1000); //加载完成后,每隔1s调用一次倒计时函数
</script>
</body>
</html>
实现效果:
参考文章:
https://www.cnblogs.com/heizai002/p/6862418.html
http://www.jb51.net/article/97501.htm