Tab 選單是內容分類最常見的介面模式。這個範例的特別之處在於「資料與介面分離」:頻道名稱與內容都放在一個陣列裡,選單項目由 JavaScript 動態產生,日後要增減分頁只需改資料,不必動 HTML。
* {
margin: 0px;
padding: 0px;
}
body {
width: 600px;
margin: 0 auto;
background-color: silver;
}
#contanier {
background-color: yellow;
width: 600px;
height: 400px;
}
#tabNavi {
width: 600px;
height: 30px;
background-color: #00bfff;
text-decoration: none;
list-style-type: none;
}
#tabNavi li {
float: left;
margin-right: 7px;
background-color: #008b8b;
color: white;
cursor: pointer;
width: 60px;
height: 28px;
line-height: 30px;
text-align: center;
}
#content {
width: 600px;
height: 370px;
background-color: white;
}
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>js 實現 tab 菜單動態切換效果</title>
<link href="css/index.css" rel="stylesheet" />
<script type="text/javascript">
function gel(id) {
return document.getElementById(id);
}
var arr = [
{ "title": "新聞", "content": "這是新聞頻道" },
{ "title": "財經", "content": "這是財經頻道" },
{ "title": "娛樂", "content": "這是娛樂頻道" },
{ "title": "體育", "content": "這是體育頻道" },
{ "title": "汽車", "content": "這是汽車頻道" },
{ "title": "視頻", "content": "這是視頻頻道" },
{ "title": "生活", "content": "這是生活頻道" }
];
window.onload = function () {
for (var i = 0; i < arr.length; i++) {
var liNew = document.createElement("li");
liNew.innerHTML = arr[i].title;
gel("tabNavi").appendChild(liNew);
// 為每個 li 設定索引屬性,供點擊時對應資料
liNew.setAttribute("id", i);
liNew.onclick = function () {
var navs = gel("tabNavi").childNodes;
// 先清除所有背景色
for (var j = 0; j < navs.length; j++) {
if (navs[j].nodeType == 1) {
navs[j].style.backgroundColor = "#008b8b";
}
}
// 再高亮目前點擊的項目
this.style.backgroundColor = "red";
// 依索引取出對應內容
gel("content").innerHTML = arr[this.id].content;
};
}
};
</script>
</head>
<body>
<div id="contanier">
<ul id="tabNavi"></ul>
<div id="content" class="content"></div>
</div>
</body>
</html>
用 id 屬性當索引。在迴圈中動態建立元素時,每個元素的 onclick 若直接引用迴圈變數 i,會遇到經典的閉包問題——所有元素拿到的都是迴圈結束後的最終值。這裡的解法是把索引寫進元素自己的 id 屬性,點擊時透過 this.id 讀回來,每個元素就記住了自己的位置。
nodeType 判斷不可省。用 childNodes 取值時,標籤間的換行會產生文字節點,必須以 nodeType == 1 過濾,否則會對空白節點設定樣式而報錯。
先全部復原、再高亮一個。這種「重置後再套用」的順序比「取消上一個、設定下一個」更簡單,也不必額外記住前一次是誰。
這個實作直接操作 style.backgroundColor,樣式與邏輯綁在一起。較好的做法是在 CSS 中定義 .active 類別,JavaScript 只負責切換 class:
navs.forEach(function (li) { li.classList.remove('active'); });
this.classList.add('active');
此外,容器 id 拼成了 contanier(正確拼法為 container),複製這段程式碼時要前後一致,否則會找不到元素。最後,若要動手重寫,用 document.createElement 搭配 textContent 而非 innerHTML 填入文字,可以避免資料中含有 HTML 特殊字元時被誤解析,也更安全。