標題
<!-- preloader -->
<div class="title">
<h2>about</h2>
<p>
...Details...
</p>
</div>
裝飾圖片
<!-- header -->
<article class="about-img">
<img src="./hero-bcg.jpeg" alt="" />
</article>
按鈕與說明欄
<!-- 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>
about
tab-btn
,id是各自類別名稱active
(下方會說明)預設所有說明欄皆不顯示 :
.content {
display: none;
}
只要按鈕加了active
,顏色就變白色 :
.tab-btn.active {
background: var(--clr-white);
}
.class.class
的作用,在【10】網頁練習 - 開合型FAQ中有提到只要說明欄加了active
,就會顯示 :
.content.active {
display: block;
}
利用class="about"
去抓取整個article
const about = document.querySelector(".about");
利用class="tab-btn"
去抓取三個按鈕
const btns = document.querySelectorAll(".tab-btn");
利用class="content"
去抓取三個說明欄
const articles = document.querySelectorAll(".content");
新增article點擊事件
about.addEventListener("click", function (e) {
//內容...
}
about.addEventListener()
中判斷出目前被點擊按鈕的類別名稱
const id = e.target.dataset.id;
判斷哪個按鈕與說明欄要加上active
if (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
,故這裡是用來判斷是否只有按鈕被點擊。無