選項卡(tab)是很基本的元件,但自己寫時常會卡在「點了標籤,怎麼知道要顯示哪一塊內容」。最乾淨的解法是用索引對位:算出被點擊標籤是第幾個,就顯示第幾個內容區塊。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>實用的 jQuery 選項卡</title>
<script src="jquery-1.9.1.min.js"></script>
<style type="text/css">
.order_box .stitle {
width: 825px;
clear: right;
height: 27px;
border-bottom: 2px solid #A10000;
}
.order_box .stitle .close { /* 未選中的標籤 */
width: 80px; height: 18px;
border: 1px solid #dedede;
border-bottom: none;
background: #f1f1f1; color: #000;
text-align: center; float: left;
margin-right: 5px; padding-top: 8px;
}
.order_box .stitle .open { /* 選中的標籤 */
width: 82px; height: 20px;
background: #A10000; color: #fff;
text-align: center; float: left;
margin-right: 5px; padding-top: 8px;
overflow: hidden;
}
.order_box ul li {
cursor: pointer;
list-style: none;
}
</style>
<script type="text/javascript">
// 選項卡切換
$(function () {
$(".stitle li").click(function () {
var index_tab = $(this).parent().children().index($(this)); // 被點標籤的索引
$(this).parent().find(".open").removeClass("open").addClass("close");
$(this).removeClass("close").addClass("open"); // 切換標籤樣式
var content_obj = $(".cntorder"); // 內容節點
content_obj.hide();
content_obj.eq(index_tab).show(); // 對位顯示
});
});
</script>
</head>
<body>
<div class="order_box">
<div class="stitle">
<ul>
<li class="open">進行中</li>
<li class="close">已完成</li>
<li class="close">無效</li>
</ul>
</div>
<div class="cntorder">tab1</div>
<div class="cntorder" style="display: none;">tab2</div>
<div class="cntorder" style="display: none;">tab3</div>
</div>
</body>
</html>
var index_tab = $(this).parent().children().index($(this));
children() 取得所有兄弟標籤,.index($(this)) 回傳「自己」在這個集合中的第幾順位。parent() 不能省——若直接對 $(this).siblings() 取 index,基準集合不同,算出來的值會有偏差。
content_obj.eq(index_tab).show();
內容區塊的順序必須與標籤順序嚴格一致,這是整個方案唯一的隱性契約。日後有人調整任一方順序而沒同步,就會出現「點第一個標籤跑出第三塊內容」的錯亂。
style="display:none;" 換成 class="cntorder hide" 搭配 .hide { display: none; },樣式與行為分離,也方便除錯時一眼看出狀態。aria 屬性。 完整的 tab 元件該有 role="tablist"、role="tab"、aria-selected、aria-controls,並支援左右方向鍵切換,螢幕閱讀器才能正確理解結構。location.hash 記住目前頁籤,重新整理後仍停在原處,也能被外部連結直接導向。min-height 緩解。nav-tabs 或原生 <details> 都各有適用場景,自己手寫的好處是完全可控、體積最小。