萬盛學電腦網

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

原生 JavaScript 實現 Tab 選項卡切換組件完整教學

零依賴原生 JS Tab 組件:從核心邏輯到完整封裝

Tab 切換是最高頻 UI 組件之一。本文實現一個支持點擊/懸停觸發、多實例共存、自定義激活類名的輕量級 Tab 組件,核心代碼不足 80 行。

核心邏輯三步走

  1. 獲取元素:按鈕組、內容組、激活類名
  2. 狀態重置:隱藏所有內容、移除所有按鈕激活類
  3. 激活目標:顯示對應內容、添加按鈕激活類

完整組件代碼 (LGY_tab)

function LGY_tab(option) {
  this.oTab_btn = this.getDom(option.tabBtn);    // 切換按鈕集合
  this.oTab_clist = this.getDom(option.tabCon);  // 內容面板集合
  if (!this.oTab_btn || !this.oTab_clist) return;
  
  this.sCur = option.cur;           // 激活類名
  this.type = option.type || 'click'; // 觸發類型:click/mouseover
  this.nLen = this.oTab_btn.length;
  this.init();
}

LGY_tab.prototype = {
  // 簡易選擇器:支持 "#id .class" 格式
  getDom(selector) {
    const [idSel, classSel] = selector.split(' ');
    const parent = document.getElementById(idSel.slice(1));
    if (!parent) return null;
    return this.getByClassName(classSel.slice(1), parent);
  },

  // 獲取類名元素(兼容舊瀏覽器)
  getByClassName(className, parent) {
    if (parent.getElementsByClassName) {
      return Array.from(parent.getElementsByClassName(className));
    }
    const regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
    const all = parent.getElementsByTagName('*');
    const result = [];
    for (let i = 0, len = all.length; i < len; i++) {
      if (regex.test(all[i].className)) result.push(all[i]);
    }
    return result;
  },

  // 重置所有狀態
  change() {
    const regex = new RegExp('(^|\\s)' + this.sCur + '(\\s|$)');
    for (let i = 0; i < this.nLen; i++) {
      this.oTab_clist[i].style.display = 'none';
      this.oTab_btn[i].className = this.oTab_btn[i].className.replace(regex, '');
    }
  },

  init() {
    // 默認激活第一個
    this.oTab_btn[0].className += ' ' + this.sCur;
    this.oTab_clist[0].style.display = 'block';
    
    // 綁定事件
    for (let i = 0; i < this.nLen; i++) {
      this.oTab_btn[i].index = i;
      this.oTab_btn[i]['on' + this.type] = () => {
        this.change();
        this.oTab_btn[i].className += ' ' + this.sCur;
        this.oTab_clist[i].style.display = 'block';
      };
    }
  }
};

HTML 結構與調用示例

<div class="box" id="tabA">
  <ul>
    <li class="tab-i">btn-A</li>
    <li class="tab-i">btn-B</li>
  </ul>
  <p class="tab-c">con-A</p>
  <p class="tab-c">con-B</p>
</div>

<script>
new LGY_tab({
  'tabBtn': '#tabA .tab-i',  // 按鈕選擇器
  'tabCon': '#tabA .tab-c',  // 內容選擇器
  'cur': 'tab-cur'           // 激活類名
});
</script>

CSS 樣式參考

.box { width: 300px; border: 1px solid #ccc; }
.box ul { height: 30px; line-height: 30px; }
.box ul li { 
  float: left; width: 150px; text-align: center; 
  background: #eee; cursor: pointer; 
}
.box .tab-cur { background: #000; color: #fff; }
.box p { display: none; padding: 30px; }

功能擴展建議

  • 動畫過渡:配合 CSS `transition: opacity .3s` + `opacity: 0/1` 替代 `display`
  • 鍵盤無障礙:添加 `keydown` 處理 ArrowLeft/Right、Home、End
  • 動態增減:提供 `addTab(btnHtml, conHtml)`、`removeTab(index)` 方法
  • 懶加載:首次激活時才請求內容數據
  • URL 同步:配合 `history.pushState` 實現可分享的 Tab 狀態

這個組件證明了:不依賴框架也能寫出優雅、可復用的 UI 組件。

copyright © 萬盛學電腦網 all rights reserved