倒計時是活動頁、限時優惠常見的功能。本文分享一段相當簡潔實用的倒計時程式碼,能夠精確到秒,並示範兩種不同的實作思路,讓讀者依需求挑選。
完整程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div id="demo01" class="colockbox">剩余 <i class="day">0</i>天 <i class="hour">0</i>時 <i class="minute">0</i>分 <i class="second">0</i>秒 <input id="end_time_gou" type="hidden" value="2015/08/20 13:00:00"> <input id="now_gou" type="hidden" value="2015/06/25 11:44:08"> </div> <div id="timer" class="colockbox"> </div> <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.0.min.js"></script> <script> var time_end = $('#end_time_gou').val(); var time_now_server = $('#now_gou').val(); countDown(time_end,time_now_server,"#demo01 .day","#demo01 .hour","#demo01 .minute","#demo01 .second"); function countDown(endtime,now,day_elem,hour_elem,minute_elem,second_elem){ var end_time = new Date(endtime).getTime(), current_time = new Date(now).getTime(), sys_second = (end_time-current_time)/1000; var timer = setInterval(function(){ if (sys_second > 0) { sys_second -= 1; var day = Math.floor((sys_second / 3600) / 24); var hour = Math.floor((sys_second / 3600) % 24); var minute = Math.floor((sys_second / 60) % 60); var second = Math.floor(sys_second % 60); day_elem && $(day_elem).text(day); $(hour_elem).text(hour<10?"0"+hour:hour); $(minute_elem).text(minute<10?"0"+minute:minute); $(second_elem).text(second<10?"0"+second:second); } else { clearInterval(timer); } }, 1000); } </script> </body> </html>
第一段以jQuery搭配 setInterval 每秒遞減,透過取餘運算分別計算天、時、分、秒,並對個位數補零。第二段則是純原生的寫法,先取得伺服器時間與本地時間的差值來校正時差,再據此計算剩餘時間,適合需要與伺服器同步的場景。
以上就是本文的全部內容,希望大家能夠喜歡。