Tab 切換是最高頻 UI 組件之一。本文實現一個支持點擊/懸停觸發、多實例共存、自定義激活類名的輕量級 Tab 組件,核心代碼不足 80 行。
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';
};
}
}
};
<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>
.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; }
這個組件證明了:不依賴框架也能寫出優雅、可復用的 UI 組件。