DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> WEB前端代碼
最經典的原生 JS Tab 頁切換實作
編輯:WEB前端代碼     

這是一個結構最直白的 Tab 頁範例:標籤用一組 <ul>,內容用另一組 <ul>,靠一個 switchTab 函式切換 class 與 display。程式碼短、邏輯清楚,很適合當作入門範本。

先看效果:

  • 新聞
  • 財經
  • 娛樂
  • JS
  • 新聞內容
  • 財經內容
  • 娛樂內容
  • Javascript 內容

完整程式碼

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title>常用tab切換</title>
<style type="text/css">
#box{width:500px;font-size:12px}
#box ul{margin:0;padding:0;list-style:none}
#box #tab{height:25px;padding-left:10px;border-bottom:1px solid #AACBEE}
#box #tab li{width:80px;height:18px;padding-top:7px;margin-right:10px;text-align:center;float:left;background:#F3F8FD;cursor:pointer}
#box #tab li.on{width:78px;height:19px;padding-top:5px;border:1px solid #AACBEE;border-bottom:none;color:#00f;background:#E8F2F7;position:relative;top:1px}
#box #tab_con{border:1px solid #AACBEE;border-top:none;padding:20px}
#box #tab_con li{display:none}
#box #tab_con #tab_con_1{display:block;}
</style>
</head>
<body>
<div id="box">
<ul id="tab">
<li class="on" id="tab_1" onclick="switchTab(1)">新聞</li>
<li id="tab_2" onclick="switchTab(2)">財經</li>
<li id="tab_3" onclick="switchTab(3)">娛樂</li>
<li id="tab_4" onclick="switchTab(4)">娛樂</li>
</ul>
<ul id="tab_con">
<li id="tab_con_1">新聞內容</li>
<li id="tab_con_2">財經內容</li>
<li id="tab_con_3">娛樂內容</li>
<li id="tab_con_4">娛樂內容3</li>
</ul>
</div>
<script type="text/javascript">
function switchTab(n){
for(var i = 1; i <= 4; i++){
document.getElementById("tab_" + i).className = "";
document.getElementById("tab_con_" + i).style.display = "none";
}
document.getElementById("tab_" + n).className = "on";
document.getElementById("tab_con_" + n).style.display = "block";
}
</script>
</body>
</html>

兩個值得注意的細節

選中態的視覺接合:li.on 把 width 從 80px 改成 78px、padding-top 從 7px 改成 5px,是為了補上新增的 1px 邊框所佔的空間,讓整體尺寸不變。再加上 border-bottom:none 與 position:relative;top:1px,選中的標籤就會壓在下方內容區的邊框上,視覺上與內容連成一體——這是做出「真的像分頁」的關鍵。

ID 命名是通用性的基礎:switchTab 靠 "tab_" + i 與 "tab_con_" + i 組出元素 ID,因此只要維持這套命名規則,就能在頁面中複製出多組互不干擾的 Tab。若要支援更多分頁,記得同步把迴圈上限 4 改成實際數量。

實務提醒:用 onclick 直接寫在標籤上不 Preferred;較好的做法是用 addEventListener 綁定事件,並從 data 屬性讀取索引。另外,若要兼顧無障礙,分頁元件應加上 role="tablist"、role="tab"、aria-selected 等屬性,讓螢幕閱讀器能理解目前的正是在哪一頁。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved