日期倒计时案例
以下是一个日期倒计时的JavaScript案例:
HTML:
<div id="countdown">
<div class="countdown-item">
<span id="days"></span>
<p>Days</p>
</div>
<div class="countdown-item">
<span id="hours"></span>
<p>Hours</p>
</div>
<div class="countdown-item">
<span id="minutes"></span>
<p>Minutes</p>
</div>
<div class="countdown-item">
<span id="seconds"></span>
<p>Seconds</p>
</div>
</div>
CSS:
#countdown {
display: flex;
justify-content: center;
}
.countdown-item {
margin: 0 10px;
text-align: center;
font-size: 30px;
}
.countdown-item p {
margin-top: 10px;
font-size: 16px;
}
JavaScript:
// Set the date we're counting down to
var countDownDate = new Date("Jan 1, 2022 00:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Calculate days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="countdown"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = seconds;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "Happy New Year!";
}
}, 1000);
这个案例将在页面上创建一个日期倒计时,以计算距离2022年1月1日的天数、小时数、分钟数和秒数。如果倒计时结束,它将显示“Happy New Year!”。
原文地址: https://www.cveoy.top/t/topic/bnG1 著作权归作者所有。请勿转载和采集!