Tab 選單幾乎每個網站都用得到。與其把七個分頁硬寫成七段 HTML,不如讓 JavaScript 根據一份資料陣列自動產生——這才是好架構的起點。
* {
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;
}
先把所有分頁的標題與內容集中在一個陣列裡。之後不論要新增還是刪除分頁,都只需要改這份資料,HTML 結構完全不用動。
var arr = [
{ "title": "新聞", "content": "這是新聞頻道" },
{ "title": "財經", "content": "這是財經頻道" },
{ "title": "娛樂", "content": "這是娛樂頻道" },
{ "title": "體育", "content": "這是體育頻道" },
{ "title": "汽車", "content": "這是汽車頻道" },
{ "title": "視頻", "content": "這是視頻頻道" },
{ "title": "生活", "content": "這是生活頻道" }
];
頁面載入後,遍歷陣列動態建立 <li>,並把索引寫進 id 屬性。這個 id 是後續點擊時找到對應內容的關鍵。
<!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 一個可辨識的 id
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";
// 依 id 取出對應內容
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>
內容與渲染分離。分頁的標題和內容量由資料決定,畫面只是資料的一種呈現方式。當你之後要把資料改成從 API 抓取,邏輯幾乎不用改動。
另外別忘了 nodeType == 1 的判斷——childNodes 會把空白文字節點一起撈回來,少了這個過濾,樣式操作就會出錯。