HTML5 時(shí)間倒計(jì)時(shí)
<!DOCTYPE html> <html> <head> <title>倒計(jì)時(shí)</title> <meta charset="UTF-8"> <script> function countDown() { var now = new Date(); //獲取當(dāng)前時(shí)間 var target = new Date("2022-01-01 00:00:00"); //設(shè)定目標(biāo)時(shí)間 var leftTime = target.getTime() - now.getTime(); //計(jì)算剩余毫秒數(shù) if (leftTime >= 0) { var days = Math.floor(leftTime / (1000 * 60 * 60 * 24)); //計(jì)算剩余天數(shù) var hours = Math.floor(leftTime / (1000 * 60 * 60) % 24); //計(jì)算剩余小時(shí)數(shù) var minutes = Math.floor(leftTime / (1000 * 60) % 60); //計(jì)算剩余分鐘數(shù) var seconds = Math.floor(leftTime / 1000 % 60); //計(jì)算剩余秒數(shù) document.getElementById("countdown").innerHTML = days + "天" + hours + "小時(shí)" + minutes + "分" + seconds + "秒"; //輸出倒計(jì)時(shí)結(jié)果 } else { document.getElementById("countdown").innerHTML = "倒計(jì)時(shí)已結(jié)束"; //輸出倒計(jì)時(shí)已結(jié)束 } setTimeout(countDown, 1000); //每隔1秒更新一次倒計(jì)時(shí) } window.onload = function() { countDown(); } </script> </head> <body> <div id="countdown"></div> </body> </html>
使用HTML5和JavaScript編寫倒計(jì)時(shí)代碼可以讓網(wǎng)頁更加生動(dòng)有趣,同時(shí)也可以增加用戶的體驗(yàn)感。以上代碼可以根據(jù)自己的需要設(shè)定目標(biāo)時(shí)間,并在頁面中輸出倒計(jì)時(shí)結(jié)果。在編寫過程中,我們需要先獲取當(dāng)前時(shí)間和目標(biāo)時(shí)間,然后計(jì)算它們之間的差值,最后根據(jù)時(shí)間差輸出對應(yīng)的剩余天數(shù)、小時(shí)數(shù)、分鐘數(shù)和秒數(shù)。通過使用setTimeout方法,我們可以每隔1秒更新一次倒計(jì)時(shí)。