萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 幾行代碼實現簡易 Tab 切換

利用索引對應:點擊標籤 <li> 取得索引,移除所有標籤 .current 類別並加到當前,同時隱藏所有內容面板 <ul> 只顯示對應索引面板。邏輯清晰、代碼極簡。

完整範例

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 簡易選項卡</title>
<style>
* { margin:0; padding:0; }
body { font:12px/1.5 Tahoma; }
#outer { width:450px; margin:10px auto; }
#tab { overflow:hidden; zoom:1; background:#000; border:1px solid #000; }
#tab li { float:left; color:#fff; height:30px; cursor:pointer; line-height:30px; list-style:none; padding:0 20px; }
#tab li.current { color:#000; background:#ccc; }
#content { border:1px solid #000; border-top-width:0; }
#content ul { line-height:25px; display:none; margin:0 30px; padding:10px 0; }
</style>
</head>
<body>
<div id="outer">
  <ul id="tab">
    <li class="current">第一課</li>
    <li>第二課</li>
    <li>第三課</li>
  </ul>
  <div id="content">
    <ul style="display:block;">1111</ul>
    <ul>2222</ul>
    <ul>3333</ul>
  </div>
</div>

<script src="https://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function() {
    var $li = $('#tab li');
    var $ul = $('#content ul');
    $li.click(function() {
        $li.removeClass();
        var idx = $(this).index();
        $(this).addClass('current');
        $ul.css('display', 'none');
        $ul.eq(idx).css('display', 'block');
    });
});
</script>
</body>
</html>

關鍵點

  • $(this).index() 取得在同輩元素中的索引(從 0 開始)。
  • $ul.eq(idx) 選取對應索引的面板。
  • 初始狀態:第一個標籤加 .current,第一個面板 style="display:block;"。

擴充建議

  • 加入 .hover() 或鍵盤支援(左右鍵切換、Enter 啟用)。
  • 動畫過渡:$ul.eq(idx).fadeIn().siblings().hide()。
  • 響應式:標籤過多時改為捲動或下拉選單。
  • 無障礙:添加 role="tablist"、aria-selected、aria-controls 等 ARIA 屬性。
copyright © 萬盛學電腦網 all rights reserved