JS倒計(jì)時(shí)兩種實(shí)現(xiàn)方式代碼實(shí)例
最近做瀏覽器界面倒計(jì)時(shí),用js就實(shí)現(xiàn),兩種方式:
一:設(shè)置時(shí)長(zhǎng),進(jìn)行倒計(jì)時(shí)。比如考試時(shí)間等等
代碼如下:
<html><head><meta charset='UTF-8'><title>簡(jiǎn)單時(shí)長(zhǎng)倒計(jì)時(shí)</title><SCRIPT type='text/javascript'> var maxtime = 60 * 60; //一個(gè)小時(shí),按秒計(jì)算,自己調(diào)整! function CountDown() {if (maxtime >= 0) { minutes = Math.floor(maxtime / 60); seconds = Math.floor(maxtime % 60); msg = '距離結(jié)束還有' + minutes + '分' + seconds + '秒'; document.all['timer'].innerHTML = msg; if (maxtime == 5 * 60)alert('還剩5分鐘'); --maxtime;} else{ clearInterval(timer); alert('時(shí)間到,結(jié)束!');} } timer = setInterval('CountDown()', 1000); </SCRIPT></head><body><div style='color:red'></div><div style='color:red'></div></body></html>
運(yùn)行結(jié)果:
二:設(shè)置時(shí)間戳,進(jìn)行倒計(jì)時(shí)。比如距離活動(dòng)結(jié)束時(shí)間等等
代碼如下:
<html><head> <meta charset='UTF-8'> <title>js簡(jiǎn)單時(shí)分秒倒計(jì)時(shí)</title> <script type='text/javascript'> function countTime() { //獲取當(dāng)前時(shí)間 var date = new Date(); var now = date.getTime(); //設(shè)置截止時(shí)間 var str='2017/5/17 00:00:00'; var endDate = new Date(str); var end = endDate.getTime(); //時(shí)間差 var leftTime = end-now; //定義變量 d,h,m,s保存倒計(jì)時(shí)的時(shí)間 var d,h,m,s; if (leftTime>=0) {d = Math.floor(leftTime/1000/60/60/24);h = Math.floor(leftTime/1000/60/60%24);m = Math.floor(leftTime/1000/60%60);s = Math.floor(leftTime/1000%60); } //將倒計(jì)時(shí)賦值到div中 document.getElementById('_d').innerHTML = d+'天'; document.getElementById('_h').innerHTML = h+'時(shí)'; document.getElementById('_m').innerHTML = m+'分'; document.getElementById('_s').innerHTML = s+'秒'; //遞歸每秒調(diào)用countTime方法,顯示動(dòng)態(tài)時(shí)間效果 setTimeout(countTime,1000); } </script></head ><body onload='countTime()' > <div> <span id='_d'>00</span> <span id='_h'>00</span> <span id='_m'>00</span> <span id='_s'>00</span> </div></body></html>
運(yùn)行結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. android 控件同時(shí)監(jiān)聽(tīng)單擊和雙擊實(shí)例2. 解決vue頁(yè)面刷新,數(shù)據(jù)丟失的問(wèn)題3. Python 忽略文件名編碼的方法4. vue路由分文件拆分管理詳解5. 詳解android adb常見(jiàn)用法6. vue+vuex+axios從后臺(tái)獲取數(shù)據(jù)存入vuex,組件之間共享數(shù)據(jù)操作7. python logging.info在終端沒(méi)輸出的解決8. android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器(無(wú)bug)9. python Selenium 庫(kù)的使用技巧10. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作
