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. idea設(shè)置代碼格式化的方法步驟2. ajax異步讀取后臺(tái)傳遞回的下拉選項(xiàng)的值方法3. 關(guān)于ajax異步訪問數(shù)據(jù)的問題4. Vue打包部署到Nginx時(shí),css樣式不生效的解決方式5. Python 調(diào)用API發(fā)送郵件6. 聊一聊數(shù)據(jù)請(qǐng)求中Ajax、Fetch及Axios的區(qū)別7. ajax異步實(shí)現(xiàn)文件分片上傳實(shí)例代碼8. Vue組件通信$attrs、$listeners實(shí)現(xiàn)原理解析9. HTML iframe標(biāo)簽用法案例詳解10. 簡(jiǎn)單明了帶你了解CSS Modules
