Countdown Timer

重點功能說明

  1. Deadline顯示區域
  2. 倒數計時器

HTML重點

  • Deadline顯示區域

    1
    <h4 class="giveaway"></h4>
    • 將Deadline顯示區域的Class設為giveaway
    • 內容會在JavaScript中新增
  • 倒數計時器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <div class="deadline">
    <!-- days -->
    <div class="deadline-format">
    <div>
    <h4 class="days">34</h4>
    <span>days</span>
    </div>
    </div>
    <!-- end of days-->

    <!-- hours -->
    <div class="deadline-format">
    <div>
    <h4 class="hours">34</h4>
    <span>hours</span>
    </div>
    </div>
    <!-- end of hours-->

    <!-- mins -->
    <div class="deadline-format">
    <div>
    <h4 class="mins">34</h4>
    <span>mins</span>
    </div>
    </div>
    <!-- end of mins-->

    <!-- secs -->
    <div class="deadline-format">
    <div>
    <h4 class="secs">34</h4>
    <span>secs</span>
    </div>
    </div>
    <!-- end of secs-->
    </div>
    • 將整個倒數計時器的Class設為deadline
    • 將個別時間單位DIV的Class設為deadline-format

JavaScript重點

  1. 建立月份與星期的陣列

    1
    2
    const months = [`January`,...];
    const weekdays = [`Sunday`,...];
  2. 利用class="giveaway"去抓取Deadline顯示區域

    1
    const giveaway = document.querySelector('.giveaway');
  3. 利用class="deadline"去抓取整個倒數計時器

    1
    const deadline = document.querySelector('.deadline');
  4. 利用class="deadline-format"中的h4元素去抓取個別時間單位的h4元素

    1
    const items = document.querySelectorAll('.deadline-format h4');
    • ququerySelector(All)方法還可以選擇該id/class的子元素,詳請請見簡單介紹
  5. 取得當前日期

    1
    2
    3
    4
    let tempDate = new Date(); //建立一個Date物件
    let tempYear = tempDate.getFullYear(); //取得當前年份
    let tempMonth = tempDate.getMonth(); //取得當前月份
    let tempDay = tempDate.getDate(); //取得當前日期
    • Date物件詳細用法,請見下方參考欄
  6. 設定Deadline日期

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const futureDate = new Date(tempYear, tempMonth, tempDay + 10, 11, 30, 0); //設定當前日期的後10天

    //取得所有時間元素
    const year = futureDate.getFullYear();
    const hours = futureDate.getHours();
    const minutes = futureDate.getMinutes();
    let month = futureDate.getMonth();
    month = months[month];
    const weekday = weekdays[futureDate.getDay()];
    const date = futureDate.getDate();
  7. 新增Deadline顯示區域的內文

    1
    giveaway.textContent = `giveaway ends on ${weekday}, ${date} ${month} ${year} ${hours}:${minutes}am`;

參考與引用來源

  1. Date物件介紹