萬盛學電腦網

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

jQuery Tab 切換組件:點擊顯示對應面板、隱藏同輩、高亮當前、懸停效果完整實現

核心邏輯

  1. 點擊 Tab 按鈕(`
  2. `)
  3. 當前按鈕添加 `.selected`,同輩移除
  4. 獲取點擊按鈕索引
  5. 顯示對應索引的面板(`.tab_box > div`),隱藏同輩面板
  6. 懸停時添加 `.hover` 樣式

完整 HTML + CSS + JS

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>jQuery Tab 切換示例</title>
  <style>
    .tab { width: 500px; margin: 20px auto; font-family: system-ui, sans-serif; }
    .tab_menu ul { display: flex; margin: 0; padding: 0; list-style: none; border-bottom: 2px solid #007bff; }
    .tab_menu li { padding: 12px 24px; cursor: pointer; background: #f5f5f5; border: 1px solid #ddd; border-bottom: none; margin-right: 4px; border-radius: 4px 4px 0 0; transition: all 0.2s; }
    .tab_menu li.hover { background: #e8f0fe; }
    .tab_menu li.selected { background: #007bff; color: white; border-color: #007bff; font-weight: 600; }
    .tab_box { border: 1px solid #ddd; border-top: none; border-radius: 0 0 4px 4px; padding: 20px; min-height: 150px; background: white; }
    .tab_box > div { display: none; animation: fadeIn 0.3s ease; }
    .tab_box > div:first-child { display: block; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
  </style>
</head>
<body>
  <div class="tab">
    <div class="tab_menu">
      <ul>
        <li class="selected">時事</li>
        <li>體育</li>
        <li>娛樂</li>
      </ul>
    </div>
    <div class="tab_box">
      <div><h3>時事新聞</h3><p>這裡是時事內容...</p></div>
      <div class="hide"><h3>體育新聞</h3><p>這裡是體育內容...</p></div>
      <div class="hide"><h3>娛樂新聞</h3><p>這裡是娛樂內容...</p></div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
  <script>
  $(function () {
    const $tabLi = $('div.tab_menu ul li');
    const $panels = $('div.tab_box > div');
    
    $tabLi.on('click', function () {
      const $this = $(this);
      const index = $tabLi.index(this);
      
      // 1. 按鈕高亮切換
      $this.addClass('selected').siblings().removeClass('selected');
      
      // 2. 面板顯示/隱藏
      $panels.eq(index).show().siblings().hide();
    });
    
    // 懸停效果
    $tabLi.hover(
      function () { $(this).addClass('hover'); },
      function () { $(this).removeClass('hover'); }
    );
    
    // 鍵盤無障礙支援
    $tabLi.on('keydown', function (e) {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        $(this).trigger('click');
      } else if (e.key === 'ArrowRight') {
        e.preventDefault();
        $(this).next('li').trigger('focus').trigger('click');
      } else if (e.key === 'ArrowLeft') {
        e.preventDefault();
        $(this).prev('li').trigger('focus').trigger('click');
      }
    });
    
    // 初始化 ARIA
    $tabLi.attr('role', 'tab').each(function(i) {
      $(this).attr({ 'aria-selected': i===0, 'aria-controls': `panel-${i}`, 'id': `tab-${i}`, 'tabindex': i===0 ? 0 : -1 });
    });
    $panels.attr('role', 'tabpanel').each(function(i) {
      $(this).attr({ 'aria-labelledby': `tab-${i}`, 'id': `panel-${i}`, 'hidden': i!==0 });
    });
  });
  </script>
</body>
</html>

關鍵 API 解析

方法作用關鍵點
.index(element)獲取元素在集合中的索引若無參數返回相對同輩索引
.eq(index)獲取指定索引的 jQuery 對象返回 jQuery 對象,可鏈式調用
.siblings()獲取所有同輩元素不包含自身
.show()/.hide()顯示/隱藏(操作 display)記錄原 display 值,hide 後 show 可恢復
.on('click', fn)事件綁定推薦用 on,支援委託、命名空間

進階擴展

1. 動態新增/刪除 Tab

function addTab(title, contentHtml) {
  const index = $tabLi.length;
  $tabLi.last().after(`
  • ${title}
  • `); $panels.last().after(`
    ${contentHtml}
    `); // 重新綁定(或用事件委託) $('div.tab_menu ul').off('click', 'li').on('click', 'li', handler); }

    2. AJAX 載入面板內容

    $tabLi.on('click', function () {
      const $panel = $panels.eq($(this).index());
      if ($panel.data('loaded')) return; // 防重複載入
      $.get($panel.data('url'), html => {
        $panel.html(html).data('loaded', true);
      });
    });

    3. 響應式:移動端變為手風琴

    @media (max-width: 600px) {
      .tab_menu ul { flex-direction: column; }
      .tab_menu li { border: 1px solid #ddd; border-radius: 4px; margin: 4px 0; }
      .tab_box > div { display: none; }
      .tab_box > div.active { display: block; }
    }
    
    // JS 切換 .active 類而非 show/hide

    無障礙 (ARIA) 完整屬性表

    角色屬性值
    Tab 列表roletablist
    Tab 按鈕roletab
    aria-selectedtrue/false
    aria-controlspanel-id
    tabindex0 (active) / -1 (inactive)
    Tab 面板roletabpanel
    aria-labelledbytab-id
    hiddentrue/false

    結語

    Tab 切換是經典 UI 模式,**核心是「索引對應」**:按鈕索引 ↔ 面板索引。jQuery 的 `.index()`、`.eq()`、`.siblings()` 使實現極其簡潔。生產環境建議補全 **ARIA 無障礙屬性**、**鍵盤導航**、**響應式降級**,並考慮將邏輯封裝為可復用插件或遷移至 Vue/React 組件化體系。

    copyright © 萬盛學電腦網 all rights reserved