简单的倒计时
倒计时就是首先我们先添加一个需要计算的时间,然后按照每秒总时间减去一秒,然后将最终的时间按照小时,分,秒显示出来。
<div class="timeout"> <h2>倒计时</h2> <label for="hours">时:</label><select id="hours" name="xl"></select><label name="outTime" class ="ot"></label> <label for="minutes">分:</label><select id="minutes" name="xl"></select><label name="outTime" class ="ot"></label> <label for="seconds">秒:</label><select id="seconds" name="xl"></select><label name="outTime" class ="ot"></label> <h2><input type="button" id="start" value="Start"/><input type="button" id="reset" value="Reset" /></h2> </div>
使用下拉选择时间,当然也可以更改为输入框,JS对输入数字的验证。
JS代码,单击开始,使用setInterval每隔一秒执行一次函数,让总的时间(换算成秒)减去1秒,然后再将计算后的时间换算成时,分,秒显示在页面。
1 window.onload=function (){ 2 var xl=document.getElementsByName('xl'); 3 for(var n=0;n<xl.length;n++){ 4 if(n==0){ 5 for(var i=0;i<24;i++){ 6 var elems=document.createElement('option'); 7 var txt=document.createTextNode(i); 8 elems.appendChild(txt); 9 xl[n].appendChild(elems); 10 } 11 } 12 else{ 13 for(var j=0;j<60;j++){ 14 var elems=document.createElement('option'); 15 var txt=document.createTextNode(j); 16 elems.appendChild(txt); 17 xl[n].appendChild(elems); 18 } 19 } 20 } 21 document.getElementById('start').onclick=function() 22 { 23 var hours=parseInt(xl[0].value); 24 var minutes=parseInt(xl[1].value); 25 var seconds=parseInt(xl[2].value); 26 var timeall=hours*60*60+minutes*60+seconds; 27 if(timeall>0){ 28 var clearId=setInterval(function (){ 29 if(timeall>0){ 30 timeall--; 31 var ou=[]; 32 ou.push(Math.floor((timeall/60)/60)); 33 ou.push(Math.floor((timeall/60)%60)); 34 ou.push((timeall%60)%60); 35 var outTime=document.getElementsByName('outTime'); 36 for(var i=0; i<outTime.length;i++){ 37 xl[i].style.display='none'; 38 outTime[i].style.display='inline-block'; 39 outTime[i].innerHTML=ou[i]; 40 } 41 }else{clearInterval(clearId);}},1000); 42 } 43 else 44 alert('Plase select your time!') 45 } 46 }

浙公网安备 33010602011771号