JavaScript 系列三:練習5
collapse 折疊效果
by applelily
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript 系列三:練習5 ── collapse 折疊效果</title>
<link rel="stylesheet" href="./js_collapse.css">
</head>
<body>
<div class="wrap">
<div class="header">FAQ 一般問與答</div>
<hr>
<button class="collapsible">Q: 如何辦理退換貨?</button>
<div class="content"><p>
A: 請參考退貨服務頁面。
</p></div>
<button class="collapsible">Q: 退款方式及退款時間?</button>
<div class="content"><p>
A: 約7-8個工作天完成退款作業。
</p></div>
<button class="collapsible">Q: 未退回的退款,是否可直接折抵新訂單?</button>
<div class="content"><p>
A: 很抱歉,重新訂購時無法直接於新訂單扣抵。
</p></div>
<button class="collapsible">Q: 發票遺失是否仍能辦理退換貨?</button>
<div class="content"><p>
A: 很抱歉,需要有發票才能辦理退換貨。
</p></div>
<button class="collapsible">Q: 什麼情況無法辦理退換貨?</button>
<div class="content"><p>
A: 超過7天退貨期限,就無法辦理。
</p></div>
</div>
</body>
<script src="./js_collapse.js"></script>
</html>
CSS
/*
Hex Color Code
#ff69b4 hotpink
#f5288f 𣶶粉色
#fff white
#f1f1f1 白色 好像是亮一點的白色
*/
.wrap{
max-width: 680px;
margin: auto;
text-align: center;
margin-top: 10vh;
padding: 20px;
border: 3px solid #ff69b4;
border-radius: 10px;
background-color: #f1f1f1;
}
.header{
font-size: 20px;
margin: 15px;
}
.collapsible{
background-color: #ff69b4;
color: #f1f1f1;
cursor: pointer;
padding: 18px;
width: 100%;
border:none;
text-align: left;
outline:none;
font-size: 15px;
}
.active,
.collapsible:hover{
background-color: #f5288f;
}
.collapsible:after{
content: '\002B'; /* 加號+的unicode */
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after{
content: '\2212';
}
.content{
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
text-align: left;
}
JavaScript
// 程式碼說明, FAQ 的展開與晰合 :
// 抓取所有 類別選取器 為 collapsible 的元素,
// 抓到之後 ,跑 for 迴圈
// 利用addEventListener 監聽當使用者按下「某個問題」的 click 事件時
// 呼叫調用函式 ,
// 調用情境(this) ,這個程式的 this 就是 button 元素,
// button 元素自動偵測是否帶有該class 並做切換"active" class
// 下一步,判斷此 button 的下一個元素,其樣式名稱為 maxHeight,
// 如果maxHeight 有值,表示目前這個問題的 答案是展開的,要將它閉合
//反之 ,則展開,並賦予scrollHeight 高度的值
var coll = document.querySelectorAll('.collapsible');
var coll = document.querySelectorAll('.collapsible');
var i;
console.log( coll);
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
// 先將所有的內容閉合
coll.forEach(function(item) {
item.classList.remove("active");
var content = item.nextElementSibling;
content.style.maxHeight = null;
});
// 再處理當前點擊的內容
this.classList.toggle("active");
console.log(this);
var content = this.nextElementSibling;
console.log('this.nextElementSibling: ' , this.nextElementSibling
)
if (content.style.maxHeight){
content.style.maxHeight = null;
console.log('展開變閉合: '+ content.style.maxHeight)
} else {
content.style.maxHeight = content.scrollHeight + "px";
console.log('閉合變展開: '+ content.style.maxHeight)
}
});
}