下面這份範例示範如何用 CSS 搭配少量 JavaScript 做出標籤卡(Tab)切換效果,滑鼠移過標籤即可切換對應的內容面板,並透過背景圖拼合呈現選中與未選中的狀態。
<style type="text/css">
body { font-size:14px; font-family:"宋體"}
ol li { margin:8px}
#con { font-size:12px; width:600px; margin:0 auto}
#tags { height:23px; width:400px; margin:0; padding:0; margin-left:10px}
#tags li { float:left; margin-right:1px; background:url(images/tagleft.gif) no-repeat left bottom; height:23px; list-style-type:none}
#tags li a { text-decoration:none; float:left; background:url(images/tagright.gif) no-repeat right bottom; height:23px; padding:0px 10px; line-height:23px; color:#999}
#tags li.emptyTag { width:4px; background:none}
#tags li.selectTag { background-position: left top; position:relative; height:25px; margin-bottom:-2px}
#tags li.selectTag a { background-position: right top; color:#000; height:25px; line-height:25px;}
#tagContent { padding:1px; background-color:#fff; border:1px solid #aecbd4;}
.tagContent { background:url(images/bg.gif) repeat-x; height:350px; padding:10px; color:#474747; width:576px; display:none}
#tagContent div.selectTag{ display:block}
</style>
</head>
<body>
<h1>標簽示例</h1>
<div id="con">
<ul id="tags">
<li><a href="javascript:void(0)" onmouseover="selectTag('tagContent0',this)">標簽一</a></li>
<li class="selectTag"><a href="javascript:void(0)" onmouseover="selectTag('tagContent1',this)">標簽二</a></li>
<li><a href="javascript:void(0)" onmouseover="selectTag('tagContent2',this)">自適應寬度的標簽</a></li>
</ul>
<div id="tagContent">
<div id="tagContent0" class="tagContent">第一個標簽的內容</div>
<div id="tagContent1" class="tagContent selectTag">第二個標簽的內容</div>
<div id="tagContent2" class="tagContent">第三個標簽的內容</div>
</div>
</div>
<script type="text/javascript">
function selectTag(showContent,selfObj){
// 操作標簽
var tag = document.getElementById("tags").getElementsByTagName("li");
var taglength = tag.length;
for(i=0; i<taglength; i++){
tag[i].className = "";
}
selfObj.parentNode.className = "selectTag";
// 操作內容
for(i=0; j=document.getElementById("tagContent"+i); i++){
j.style.display = "none";
}
document.getElementById(showContent).style.display = "block";
}
</script>
</body>
整體原理是:所有內容面板預設 display:none,選中的加上 selectTag 類使其顯示;標籤的選中狀態則透過切換 class 與背景定位來呈現。你可以替換其中的背景圖,靈活調整標籤的外觀。