用js写倒计时
2016-12-28 16:53
253 查看
写倒计时,首先我们需要想到的是要设定时间和获取当前时间,然后两者相减就可以。但是这里需要注意的是天、时、分、秒的换算,时分秒为单数时,前面要加零占位。
方法一:
也可以用另外一种思路来写:(为了简便,就用a和b来写了=。=)
方法一:
<body> <div id="times_wrap" class="time_num"> <p>距离结束时间:</p> <div class="time_w"> <b id="times_d" class="time"> </b>天 <b id="times_h" class="time"> </b>时 <b id="times_m" class="time"> </b>分 <b id="times_s" class="time"> </b>秒 </div> </div> </body>
<script type="text/javascript"> var times = setTimeout("show_time()",1000); var time_wrap = document.getElementById("times_wrap"); var time_d = document.getElementById("times_d"); var time_h = document.getElementById("times_h"); var time_m = document.getElementById("times_m"); var time_s = document.getElementById("times_s"); var time_end = new Date("2016/12/28 16:14:00"); // 设定结束时间 time_end = time_end.getTime(); function show_time(){ var time_now = new Date(); // 获取当前时间 time_now = time_now.getTime(); var time_distance = time_end - time_now; // 结束时间减去当前时间 var int_day, int_hour, int_minute, int_second; if(time_distance >= 0){ // 天时分秒换算 int_day = Math.floor(time_distance/86400000); time_distance -= int_day * 86400000; int_hour = Math.floor(time_distance/3600000); time_distance -= int_hour * 3600000; int_minute = Math.floor(time_distance/60000); time_distance -= int_minute * 60000; int_second = Math.floor(time_distance/1000); // 时分秒为单数时、前面加零占位 if(int_hour < 10) int_hour = "0" + int_hour; if(int_minute < 10) int_minute = "0" + int_minute; if(int_second < 10) int_second = "0" + int_second; // 显示时间 time_d.innerHTML = int_day; time_h.innerHTML = int_hour; time_m.innerHTML = int_minute; time_s.innerHTML = int_second; setTimeout("show_time()",1000); }else{ alert("停止"); clearTimeout(times) } } </script>
也可以用另外一种思路来写:(为了简便,就用a和b来写了=。=)
< d2e9 ;p id="p1">0:01:03</p> <p id="p2"></p>
<script> var day_time=document.getElementById("p1"); var new_time=document.getElementById("p2"); var a=day_time.innerHTML; var b=a.split(":"); function time() { b[2]--; if(b[2]<10){ b[2]="0"+b[2]; if(b[2]==0&&b[1]>0){//秒 b[2]=59; b[1]=b[1]-1; if(b[1]<10){ b[1]="0"+b[1];} } } if(b[1]==0&&b[0]>0){//分 b[1]=59; b[0]=b[0]-1; } if(b[0]==0&&b[1]==0&&b[2]==0){//时 clearInterval(tt); } new_time.innerHTML=b[0]+":"+b[1]+":"+b[2]; } var tt=setInterval(time,1000); </script>
相关文章推荐