JS倒计时两种种实现方式

<p>JS倒计时两种种实现方式</p><p></p><p>一:设置时长,进行倒计时。比如考试时间等等</p><pre class="brush:html;toolbar:false">1&lt;html&gt; 2&lt;head&gt; 3&lt;metacharset=&quot;UTF-8&quot;&gt; 4&lt;title&gt;简单时长倒计时&lt;/title&gt; 5&lt;SCRIPTtype=&quot;text/javascript&quot;&gt; 6varmaxtime=60*60;//一个小时,按秒计算,自己调整! 7functionCountDown(){ 8if(maxtime&gt;=0){ 9minutes=Math.floor(maxtime/60); 10seconds=Math.floor(maxtime%60); 11msg=&quot;距离结束还有&quot;+minutes+&quot;分&quot;+seconds+&quot;秒&quot;; 12document.all[&quot;timer&quot;].innerHTML=msg; 13if(maxtime==5*60)alert(&quot;还剩5分钟&quot;); 14--maxtime; 15}else{ 16clearInterval(timer); 17alert(&quot;时间到,结束!&quot;); 18} 19} 20timer=setInterval(&quot;CountDown()&quot;,1000); 21&lt;/SCRIPT&gt; 22&lt;/head&gt; 23&lt;body&gt; 24&lt;divid=&quot;timer&quot;style=&quot;color:red&quot;&gt;&lt;/div&gt; 25&lt;divid=&quot;warring&quot;style=&quot;color:red&quot;&gt;&lt;/div&gt; 26&lt;/body&gt; 27&lt;/html&gt;</pre><p><br/></p><p>二:设置时间戳,进行倒计时。比如距离活动结束时间等等</p><p><br/></p><pre class="brush:html;toolbar:false">1&lt;html&gt; 2&lt;head&gt; 3&lt;metacharset=&quot;UTF-8&quot;&gt; 4&lt;title&gt;js简单时分秒倒计时&lt;/title&gt; 5&lt;scripttype=&quot;text/javascript&quot;&gt; 6functioncountTime(){ 7//获取当前时间 8vardate=newDate(); 9varnow=date.getTime(); 10//设置截止时间 11varstr=&quot;2017/5/1700:00:00&quot;; 12varendDate=newDate(str); 13varend=endDate.getTime(); 14 15//时间差 16varleftTime=end-now; 17//定义变量d,h,m,s保存倒计时的时间 18vard,h,m,s; 19if(leftTime&gt;=0){ 20d=Math.floor(leftTime/1000/60/60/24); 21h=Math.floor(leftTime/1000/60/60%24); 22m=Math.floor(leftTime/1000/60%60); 23s=Math.floor(leftTime/1000%60); 24} 25//将倒计时赋值到div中 26document.getElementById(&quot;_d&quot;).innerHTML=d+&quot;天&quot;; 27document.getElementById(&quot;_h&quot;).innerHTML=h+&quot;时&quot;; 28document.getElementById(&quot;_m&quot;).innerHTML=m+&quot;分&quot;; 29document.getElementById(&quot;_s&quot;).innerHTML=s+&quot;秒&quot;; 30//递归每秒调用countTime方法,显示动态时间效果 31setTimeout(countTime,1000); 32 33} 34&lt;/script&gt; 35&lt;/head&gt; 36&lt;bodyonload=&quot;countTime()&quot;&gt;</pre>
RangeTime:0.008220s
RangeMem:206.08 KB
返回顶部 留言