页面需要制作一个倒计时的功能;然后度娘了一遍,找到两种写法,原生JS与JQ 的,经过测试原生JS在IE可能会有不刷新的现象所以结合了一个大神的JQ写法修改好了一个。
原生JS写法:
HTML:
<div class="time"> <span id="t_d"></span> <span id="t_h"></span> <span id="t_m"></span> <span id="t_s"></span> </div>
JS:
<script> function GetRTime(){ var EndTime= new Date(‘2015/06/19 22:00:00‘); var NowTime = new Date(); var t =EndTime.getTime() - NowTime.getTime(); var d=Math.floor(t/1000/60/60/24); var h=Math.floor(t/1000/60/60%24); var m=Math.floor(t/1000/60%60); var s=Math.floor(t/1000%60); document.getElementById("t_d").innerHTML = d + "天"; document.getElementById("t_h").innerHTML = h + "时"; document.getElementById("t_m").innerHTML = m + "分"; document.getElementById("t_s").innerHTML = s + "秒"; } setInterval(GetRTime,0); </script>
这种写法,JS部分很容易看懂。
结合JQ修改后的版本:
HTML部分和上面是一样的,主要是JS部分:
<script type="text/javascript"> var EndTime= new Date(‘2015/06/19 22:00:00‘); var NowTime = new Date(); var t =EndTime.getTime() - NowTime.getTime(); var intDiff = parseInt(t/1000);//倒计时总秒数量,因为是以毫秒为单位的所以除以1000是秒 function timer(intDiff){ window.setInterval(function(){ var day=0, hour=0, minute=0, second=0;//时间默认值 if(intDiff > 0){ day = Math.floor(intDiff / (60 * 60 * 24)); hour = Math.floor(intDiff / (60 * 60)) - (day * 24); minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60); second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60); } if (hour <= 9) hour = ‘0‘ + hour; if (minute <= 9) minute = ‘0‘ + minute; if (second <= 9) second = ‘0‘ + second; $(‘#t_d‘).html(day+"天"); $(‘#t_h‘).html(hour+‘时‘); $(‘#t_m‘).html(minute+‘分‘); $(‘#t_s‘).html(second+‘秒‘); intDiff--; }, 1000); } $(function(){ timer(intDiff); }); </script>
时间: 2024-11-06 18:49:17