【從零開始學JavaScript】實作練習 - Scroll網頁實作(中)
Scroll
JavaScript重點
Footer中的年份顯示
- 利用
id="date"去抓取Footer中的年份1
const date = document.getElementById("date");
- 新增Date物件,並用
getFullYear()取得今年的年份,最後將其設為date的內容1
date.innerHTML = new Date().getFullYear();
- 最後結果呈現 :

- 利用
選單開啟與關閉
利用
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
3navToggle.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等屬性。 - 詳細介紹請見下方參考欄
- 量測元素包含border的大小,並回傳一個
設定選單開啟與收回
- 此時選單<ul>的相對高度(也就是
linksHeight)為200px,因為一個連結按鈕為50px1
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;
}
});
- 此時選單<ul>的相對高度(也就是
最後結果呈現 :

我們在前幾個專案的選單按鈕,都是使用了
classList.toggle()來快速設定按鈕開與關。但在這次專案中,我們用設定選單高度來製作選單開關的效果,而用此方法能更精準地控制選單開關的高度。
引用與參考連結
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


