選項卡是最基礎的互動元件之一:一排標籤,點哪個就顯示哪個的內容,其餘隱藏。重點在於「一次只顯示一個」這個不變式該如何維護。
<html>
<head>
<meta charset="utf-8"/>
<style type="text/css">
* { margin:0; padding:0; border:0 }
#main { width:300px; height:300px; background-color:green }
#head { height:50px; background-color:red }
#head li {
float:left; list-style:none; height:50px; width:72px;
text-align:center; line-height:50px;
background-color:orange; margin-right:3px; cursor:pointer;
}
</style>
</head>
<body>
<div id="main">
<div id="head">
<ul>
<li id="tab1" onclick="show(1)" style="background-color:green">新聞</li>
<li id="tab2" onclick="show(2)">體育</li>
<li id="tab3" onclick="show(3)">音樂</li>
<li id="tab4" onclick="show(4)">娛樂</li>
</ul>
</div>
<div id="content">
<p id="p1">第一則內容</p>
<p id="p2" style="display:none">第二則內容</p>
<p id="p3" style="display:none">第三則內容</p>
<p id="p4" style="display:none">第四則內容</p>
</div>
</div>
<script>
function show(n) {
for (var i = 1; i <= 4; i++) {
// 先把所有標籤重設為未選取、內容全部隱藏
document.getElementById("tab" + i).style.backgroundColor = 'orange';
document.getElementById("p" + i).style.display = 'none';
}
// 再把第 n 個設為選取並顯示
document.getElementById("tab" + n).style.backgroundColor = 'green';
document.getElementById("p" + n).style.display = "block";
}
</script>
</body>
</html>
關鍵在 show 的結構:先用迴圈「全部歸零」,再設定「唯一例外」。這種「先重置、再套用」的模式保證了任何時刻最多只有一個面板開啟,不必去判斷「目前開的是哪一個、要不要先關掉它」。狀態切換的程式碼越少,越不容易出 bug。
用 class 取代 inline style。直接改 style.backgroundColor 會覆蓋掉原本的樣式設定,也無法使用 hover 等虛擬類別。改成切換 class:
.tab { background: orange; }
.tab.active { background: green; }
function show(n) {
document.querySelectorAll('#head li').forEach(function (li, i) {
li.classList.toggle('active', i === n - 1);
li.setAttribute('aria-selected', i === n - 1 ? 'true' : 'false');
});
document.querySelectorAll('#content p').forEach(function (p, i) {
p.hidden = (i !== n - 1);
});
}
用 hidden 屬性取代 display:none。hidden 語意明確,且會被輔具正確忽略。
無障礙標記不可省。選項卡的標準結構需要 role="tablist"、role="tab"、aria-selected、aria-controls,面板則要 role="tabpanel"。同時應該支援左右方向鍵在標籤之間移動,並符合 tab 的鍵盤操作慣例。這些不是裝飾,而是讓鍵盤與螢幕閱讀器使用者能完成同樣操作的必需條件。
硬編碼的 4 是隱形陷阱。一旦標籤數量變動,迴圈上限也要跟著改。請用 tabs.length 動態取得,或改用資料驅動的方式由陣列渲染整個元件。