css倒计时代码

以下是一个简单的CSS倒计时代码示例:

HTML代码:

<div id="countdown">
  <div class="countdown-item">
    <span id="days">00</span>
    <span>Days</span>
  </div>
  <div class="countdown-item">
    <span id="hours">00</span>
    <span>Hours</span>
  </div>
  <div class="countdown-item">
    <span id="minutes">00</span>
    <span>Minutes</span>
  </div>
  <div class="countdown-item">
    <span id="seconds">00</span>
    <span>Seconds</span>
  </div>
</div>

CSS代码:

#countdown {
  display: flex;
  justify-content: center;
  align-items: center;
}

.countdown-item {
  margin: 0 10px;
  text-align: center;
}

.countdown-item span {
  display: block;
  font-size: 24px;
}

.countdown-item span:first-child {
  font-size: 48px;
  font-weight: bold;
}

JavaScript代码:

// 设置目标日期和时间
var targetDate = new Date("2022-01-01T00:00:00").getTime();

// 更新倒计时
function updateCountdown() {
  var currentDate = new Date().getTime();
  var remainingTime = targetDate - currentDate;

  var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
  var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

  document.getElementById("days").innerText = days.toString().padStart(2, "0");
  document.getElementById("hours").innerText = hours.toString().padStart(2, "0");
  document.getElementById("minutes").innerText = minutes.toString().padStart(2, "0");
  document.getElementById("seconds").innerText = seconds.toString().padStart(2, "0");
}

// 每秒更新一次倒计时
setInterval(updateCountdown, 1000);

这段代码会创建一个简单的倒计时,显示剩余的天数、小时数、分钟数和秒数。你可以根据需要自定义样式和目标日期。