CSS倒計(jì)時(shí)是一個(gè)非常有用的功能,可以以視覺上的方式提示用戶剩余時(shí)間。它可以用于各種用例,例如網(wǎng)頁上的會(huì)員計(jì)劃,限時(shí)優(yōu)惠等等。下面是一個(gè)簡(jiǎn)單的CSS倒計(jì)時(shí)的設(shè)置方法:
<html> <head> <style> .timer { font-weight: bold; font-size: 24px; } .timer:after { content: ""; display: block; width: 100%; height: 2px; background-color: #000; margin-top: 10px; } .timer span { font-size: 36px; color: #F00; } .timer span:after { content: ":"; } .timer .hours span:before, .timer .minutes span:before, .timer .seconds span:before { content: "0"; } .timer .hours span, .timer .minutes span, .timer .seconds span { display: inline-block; width: 25px; text-align: center; } </style> </head> <body> <div class="timer"> <span class="hours"><span></span></span> <span class="minutes"><span></span></span> <span class="seconds"><span></span></span> </div> <script> function countdown() { var now = new Date(); var countTo = new Date("2021-12-31"); var totalSeconds = parseInt((countTo - now) / 1000); var hours = parseInt(totalSeconds / 3600) % 24; var minutes = parseInt(totalSeconds / 60) % 60; var seconds = totalSeconds % 60; document.querySelector(".hours span").textContent = hours; document.querySelector(".minutes span").textContent = minutes; document.querySelector(".seconds span").textContent = seconds; } setInterval(countdown, 1000); </script> </body> </html>
上面的代碼中使用了一個(gè)名為“timer”的CSS類,用于設(shè)置樣式。倒計(jì)時(shí)的時(shí)間通過JavaScript來計(jì)算,并在頁面上呈現(xiàn)。
倒計(jì)時(shí)的計(jì)算非常簡(jiǎn)單,只需獲取當(dāng)前時(shí)間和未來時(shí)間的差值,然后將其轉(zhuǎn)換為小時(shí),分鐘和秒數(shù)即可。最后,使用JavaScript的setInterval()函數(shù)每秒調(diào)用一次countdown()函數(shù),以更新計(jì)時(shí)器。
希望這篇文章能對(duì)您有所幫助,讓您能夠快速創(chuàng)建一個(gè)漂亮的CSS倒計(jì)時(shí)!