萬盛學電腦網

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

JavaScript + CSS 實現 Tab 菜單切換效果(動態生成標籤)

CSS 佈局 (index.css)

* { margin:0; padding:0; }
body { width:600px; margin:0 auto; background:silver; }
#contanier { background:yellow; width:600px; height:400px; }
#tabNavi { width:600px; height:30px; background:#00bfff; list-style:none; }
#tabNavi li { float:left; margin-right:7px; background:#008b8b; color:white; cursor:pointer; width:60px; height:28px; line-height:30px; text-align:center; }
#content { width:600px; height:370px; background:white; }

HTML + JS (index.html)

<!DOCTYPE html>
<html><head>
<meta charset="utf-8"/><title>Tab 切換</title>
<link href="css/index.css" rel="stylesheet"/>
<script>
function gel(id){ return document.getElementById(id); }
var tabs = [
  {title:"新聞", content:"這是新聞頻道"},
  {title:"財經", content:"這是財經頻道"},
  {title:"娛樂", content:"這是娛樂頻道"},
  {title:"體育", content:"這是體育頻道"},
  {title:"汽車", content:"這是汽車頻道"},
  {title:"視頻", content:"這是視頻頻道"},
  {title:"生活", content:"這是生活頻道"}
];
window.onload = function(){
  tabs.forEach(function(tab, i){
    var li = document.createElement("li");
    li.innerHTML = tab.title;
    li.id = i;
    gel("tabNavi").appendChild(li);
    li.onclick = function(){
      var navs = gel("tabNavi").childNodes;
      for(var j=0;j

關鍵點

  • 數據驅動:tabs 數組集中管理標題與內容,易維護擴展。
  • 動態創建 li 並綁定索引 id,點擊時通過 this.id 獲取對應內容。
  • 切換時重置所有標籤樣式,高亮當前。

現代改寫(ES6 + 事件委託)

const tabs = [...]; // 同上
const nav = document.getElementById("tabNavi");
const content = document.getElementById("content");
nav.innerHTML = tabs.map((t,i)=>`
  • ${t.title}
  • `).join(""); nav.addEventListener("click", e=>{ if(e.target.tagName==="LI"){ [...nav.children].forEach(li=>li.style.backgroundColor="#008b8b"); e.target.style.backgroundColor="red"; content.textContent = tabs[e.target.dataset.index].content; } });
    copyright © 萬盛學電腦網 all rights reserved