Scroll

JavaScript重點

  1. Footer中的年份顯示

    • 利用id="date"去抓取Footer中的年份
      1
      const date = document.getElementById("date");
    • 新增Date物件,並用getFullYear()取得今年的年份,最後將其設為date的內容
      1
      date.innerHTML = new Date().getFullYear();
    • 最後結果呈現 :
  2. 選單開啟與關閉

    • 利用class="nav-toggle"去抓取選單按鈕

      1
      const navToggle = document.querySelector(".nav-toggle");
    • 利用class="links-containe"去抓取整個按鈕選單<div>

      1
      const linksContainer = document.querySelector(".links-container");
    • 利用class="links"去抓取整個按鈕選單<ul>

      1
      const links = document.querySelector(".links");
    • 對選單按鈕新增點擊事件

      1
      2
      3
      navToggle.addEventListener("click", function () {
      // 內容...
      });

      以下程式碼皆包含於navToggle.addEventListener()

    • 取得選單<ul>與選單<div>的相對高度

      1
      2
      3
      4
      5
      //取得選單<ul>的相對高度
      const linksHeight = links.getBoundingClientRect().height;

      //取得選單<div>的相對高度
      const containerHeight = linksContainer.getBoundingClientRect().height;
      • Element.getBoundingClientRect() :
        • 量測元素包含border的大小,並回傳一個DOMRect物件,其中包含了x / y/ width/ height/ top/ right/ bottom/ left等屬性。
        • 詳細介紹請見下方參考欄
    • 設定選單開啟與收回

      • 此時選單<ul>的相對高度(也就是linksHeight)為200px,因為一個連結按鈕為50px
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
          // 若選單<div>相對高度為0px(也就是收合時)
        if (containerHeight === 0) {

        //選單<div>相對高度變成200px(選單也就會顯示出來)
        linksContainer.style.height = `${linksHeight}px`;

        //若選單<div>相對高度為200px(也就是開啟時)
        } else {

        //選單<div>相對高度變成0px(選單也就會收回)
        linksContainer.style.height = 0;
        }
        });
    • 最後結果呈現 :

    • 我們在前幾個專案的選單按鈕,都是使用了classList.toggle()來快速設定按鈕開與關。但在這次專案中,我們用設定選單高度來製作選單開關的效果,而用此方法能更精準地控制選單開關的高度。


引用與參考連結

  1. getBoundingClientRect()介紹