1. 程式人生 > 實用技巧 >構建一個倒數計時器

構建一個倒數計時器

HTML程式碼部分:

<div id="clockdiv">
  <div>
    <span class="days"></span>
    <div class="smalltext"></div>
  </div>
  <div>
    <span class="hours"></span>
    <div class="smalltext">小時</div>
  </div>
  <div>
    <span 
class="minutes"></span> <div class="smalltext">分鐘</div> </div> <div> <span class="seconds"></span> <div class="smalltext"></div> </div> </div>

CSS程式碼部分:

main {
  text-align: center;
  background: #00ecb9;
  font-family: sans-serif
; font-weight: 100; } #clockdiv { font-family: sans-serif; color: #fff; display: inline-block; font-weight: 100; text-align: center; font-size: 30px; margin: 50px 0; } #clockdiv > div { padding: 10px; border-radius: 3px; background: #00bf96; display: inline-block; } #clockdiv div > span
{ padding: 15px; border-radius: 3px; background: #00816a; display: inline-block; } .smalltext { padding-top: 5px; font-size: 16px; }

Javascript程式碼部分:

function getTimeRemaining(endtime) {
  const total = Date.parse(endtime) - Date.parse(new Date());
  const seconds = Math.floor((total / 1000) % 60);
  const minutes = Math.floor((total / 1000 / 60) % 60);
  const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
  const days = Math.floor(total / (1000 * 60 * 60 * 24));

  return {
    total,
    days,
    hours,
    minutes,
    seconds,
  };
}

function initializeClock(id, endtime) {
  const clock = document.getElementById(id);
  const daysSpan = clock.querySelector(".days");
  const hoursSpan = clock.querySelector(".hours");
  const minutesSpan = clock.querySelector(".minutes");
  const secondsSpan = clock.querySelector(".seconds");

  function updateClock() {
    const t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ("0" + t.hours).slice(-2);
    minutesSpan.innerHTML = ("0" + t.minutes).slice(-2);
    secondsSpan.innerHTML = ("0" + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  const timeinterval = setInterval(updateClock, 1000);
}

const deadline = new Date(
  Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000
);
initializeClock("clockdiv", deadline);