本篇文章給大家帶來的內容是關于javascript中倒計時的原理與實例介紹(代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
倒計時原理:未來的時間點-現在的時間點// 現在的時間點(在變) var iNow = new Date();
// 未來的時間點(不變)
//下面兩種方法都可以定義未來的時間點 // var iNew = new Date( 2013, 10, 27, 21,56,0 ); var iNew = new Date( 'November 27,2013 22:3:0' ); // 數字形式:new Date( 2013,4,1,9,48,12 ); // 字符串形式:new Date('June 10,2013 12:12:12'); // January、February、March、April、May、June、 // July、August、September、October、November、December
var t = Math.floor((iNew - iNow)/1000); 除以1000將毫秒變為秒,因為可能出現小數,所以向下取整
// 天:Math.floor(t/86400) 未來時間與現在相差多少天
// 時:Math.floor(t%86400/3600) 未來時間與現在相差多少小時
// 分:Math.floor(t%86400%3600/60) 未來時間與現在相差多少分鐘
// 秒:t%60 未來時間與現在相差多少秒
倒計時實例:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標題文檔</title> <style> .t1 { width:400px; } </style> <script> /* var t = Math.floor( new Date().getTime()/1000 ); alert( Math.floor(t/86400)+'天'+Math.floor(t%86400/3600)+'時'+Math.floor(t%86400%3600/60)+'分'+t%60+'秒' ); */ window.onload = function () { var aInp = document.getElementsByTagName('input'); var iNow = null; var iNew = null; var t = 0; var str = ''; var timer = null; aInp[2].onclick = function () { iNew = new Date(aInp[0].value); clearInterval( timer ); timer = setInterval (function (){ iNow = new Date(); t = Math.floor( ( iNew - iNow ) / 1000 ); if ( t >= 0 ) { str = Math.floor(t/86400)+'天'+Math.floor(t%86400/3600)+'時'+Math.floor(t%86400%3600/60)+'分'+t%60+'秒'; aInp[1].value = str; } else { clearInterval( timer ); } }, 1000); }; }; </script> </head> <body> 距離:<input class="t1" type="text" value="November 27,2013 22:3:0" /><br /> 還剩:<input class="t1" type="text" /> <input type="button" value="開始倒計時吧" /> </body> </html>
相關推薦:
JS實現的倒計時效果實例(2則實例)_javascript技巧
js實現的倒計時按鈕實例_javascript技巧
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com