【從零開始學JavaScript】實作練習 - Tabs選單
Tabs
功能說明

- 標題
- 裝飾圖片
- 按鈕與說明欄
HTML重點
標題
1
2
3
4
5
6
7<!-- preloader -->
<div class="title">
<h2>about</h2>
<p>
...Details...
</p>
</div>裝飾圖片
1
2
3
4<!-- header -->
<article class="about-img">
<img src="./hero-bcg.jpeg" alt="" />
</article>按鈕與說明欄
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<!-- header -->
<article class="about">
<!-- btn container -->
<div class="btn-container">
<button class="tab-btn active" data-id="history">history</button>
<button class="tab-btn" data-id="vision">vision</button>
<button class="tab-btn" data-id="goals">goals</button>
</div>
<div class="about-content">
<!-- single item -->
<div class="content active" id="history">
<h4>history</h4>
<p>Details</p>
</div>
<!-- end of single item -->
<!-- single item -->
<div class="content" id="vision">
<h4>vision</h4>
<p>Details</p>
</div>
<!-- end of single item -->
<!-- single item -->
<div class="content" id="goals">
<h4>goals</h4>
<p>Details</p>
</div>
<!-- end of single item -->
</div>
</article>- 重點 :
- 整個article的Class是
about - 三個按鈕Class都是
tab-btn,id是各自類別名稱 - 說明Class也是各自類別名稱
- 預設History按鈕與說明欄的Class是
active(下方會說明)
- 整個article的Class是
- 重點 :
CSS重點
預設所有說明欄皆不顯示 :
1
2
3.content {
display: none;
}只要按鈕加了
active,顏色就變白色 :1
2
3.tab-btn.active {
background: var(--clr-white);
}- 這種
.class.class的作用,在【10】網頁練習 - 開合型FAQ中有提到
- 這種
只要說明欄加了
active,就會顯示 :1
2
3.content.active {
display: block;
}
JavaScript重點
利用
class="about"去抓取整個article1
const about = document.querySelector(".about");
利用
class="tab-btn"去抓取三個按鈕1
const btns = document.querySelectorAll(".tab-btn");
利用
class="content"去抓取三個說明欄1
const articles = document.querySelectorAll(".content");
新增article點擊事件
1
2
3about.addEventListener("click", function (e) {
//內容...
}- 將article新增事件,以達到可以同時控制按鈕與說明欄
- 以下程式碼皆包含於
about.addEventListener()中
判斷出目前被點擊按鈕的類別名稱
1
const id = e.target.dataset.id;
判斷哪個按鈕與說明欄要加上
active1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16if (id) { //見下面說明欄
// remove selected from other buttons
btns.forEach(function (btn) {
btn.classList.remove("active"); //移除其他按鈕的active
e.target.classList.add("active"); //對目前目標按鈕新增active
});
// hide other articles
articles.forEach(function (article) {
article.classList.remove("active"); //移除其他說明欄的active
});
const element = document.getElementById(id);
element.classList.add("active"); //對目前目標說明欄新增active
}
- 在
about點擊事件中,按鈕與說明欄都可以點擊。但在第四點的id,按鈕會回傳其類別名字,而說明欄卻會回傳undefine。所以第5點的if(id)判斷式中,只有id=類別名字才會是true,id=undefine則是false,故這裡是用來判斷是否只有按鈕被點擊。
參考與引用來源
無
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


