經典的 Tab 切換效果,用 jQuery 幾行就能完成。這個版本走的是原生 JS 的分類比對思路:用 id 當作 class 名稱的線索,點到哪個標籤就顯示對應的內容區塊。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Tab 範例</title>
<script src="https://img.poluoluo.com/jslib/jquery/jquery.js" type="text/javascript"></script>
<style type="text/css">
.tab {
background-color: #FAFAFA;
margin: 5px 8px;
padding: 5px 10px;
}
.tab p span {
background-color: #EFEFEF;
border: 1px solid #CCCCCC;
cursor: pointer;
margin-right: 6px;
padding: 2px 5px;
}
.tab p span.current {
background-color: #FAFAFA;
border-bottom-color: #fafafa; /* 讓選中標籤與內容區塊視覺融合 */
}
.tab p {
border-bottom: 1px solid #CCCCCC;
font-weight: bold;
padding: 0 10px 2px;
}
.tab li {
border-bottom: 1px dotted #CCCCCC;
padding-bottom: 3px;
margin: 5px 0;
}
.tab .mhot, .tab .allhot { display: none; }
</style>
<script type="text/javascript">
$(document).ready(function () {
$(".tab span:first").addClass("current"); // 第一個標籤設為作用中
$(".tab ul:not(:first)").hide(); // 隱藏其餘內容區塊
$(".tab span").mouseover(function () {
$(".tab span").removeClass("current"); // 先清掉所有標籤的樣式
$(this).addClass("current"); // 再標記目前這個
$(".tab ul").hide(); // 隱藏全部內容
$("." + $(this).attr("id")).fadeIn('slow'); // 依 id 值找到對應 class 顯示
});
});
</script>
</head>
<body>
<div class="tab">
<p>
<span id="tab1">tab1</span>
<span id="tab2">tab2</span>
<span id="tab3">tab3</span>
</p>
<ul class="tab1">
<li></li>
<li>www.poluoluo.com</li>
<li>我和我</li>
</ul>
<ul class="tab2">
<li>一花一世辦</li>
<li>一草一天堂</li>
</ul>
<ul class="tab3">
<li>阿裡巴巴</li>
<li>阿裡巴巴</li>
<li>一草一天堂</li>
<li>我和我的祖國</li>
<li>最愛的地方</li>
</ul>
</div>
</body>
</html>
示範頁面:https://demo.poluoluo.com/js/jquery_tab/index.htm
id 與 class 對應。span#tab1 對應 ul.tab1,透過 $("." + $(this).attr("id")) 動態組出選擇器。這種約定讓新增一個分頁時不必改 JS,只要補上一組 span 與 ul 即可。
先全清再全隱。切換時先把所有標籤的 current 拿掉、把所有內容藏起來,再顯示目標。這比逐一比對舊狀態簡單,也不容易留下殘留狀態。
初始狀態要顯式設定。span:first 加上 current、ul:not(:first) 隱藏,兩步都做才不會出現「第一頁有底線但內容是空的」這種情況。
範例用的是 mouseover,實務上多數人期待的是「點擊才切換」,把 mouseover 換成 click 即可。另外 fadeIn('slow') 每次切換都會重播動畫,快速連續點擊時容易出現閃爍,可在顯示前先呼叫 .stop(true, true) 停掉未完成的動畫。
若在意無障礙,建議改用 <a> 或 <button> 作為標籤並加上 role="tab"、aria-selected 等屬性,讓螢幕閱讀器與鍵盤使用者也能操作。