DIV CSS 佈局教程網

實用的 jQuery 選項卡切換範例:以索引對位內容面板
編輯:JQuery特效代碼     

選項卡(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();

內容區塊的順序必須與標籤順序嚴格一致,這是整個方案唯一的隱性契約。日後有人調整任一方順序而沒同步,就會出現「點第一個標籤跑出第三塊內容」的錯亂。

幾個可以再講究的地方

  • 用 class 而非 inline style 控制顯示。 把 style="display:none;" 換成 class="cntorder hide" 搭配 .hide { display: none; },樣式與行為分離,也方便除錯時一眼看出狀態。
  • 加上 aria 屬性。 完整的 tab 元件該有 role="tablist"、role="tab"、aria-selected、aria-controls,並支援左右方向鍵切換,螢幕閱讀器才能正確理解結構。
  • 可加入深層連結。 用 location.hash 記住目前頁籤,重新整理後仍停在原處,也能被外部連結直接導向。
  • 高度問題。 若各面板高度不一,切換時整個頁面會跳動,實務上常給內容區一個 min-height 緩解。
  • 懶人方案。 若不缺 jQuery 之外的其他依賴,Bootstrap 的 nav-tabs 或原生 <details> 都各有適用場景,自己手寫的好處是完全可控、體積最小。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved