點擊頂部控制按鈕,下方列表內容無縫切換,全程零 JavaScript,純 CSS3 實現。
<input type="radio"> 作為狀態持有者(互斥單選)。:checked 偽類 + 兄弟選擇器 ~ 控制對應面板顯示/隱藏。opacity:0 隱藏原生 radio,配合 label 或相鄰 .control 元素作為可見觸發區。<div class="content">
<!-- 控制器區 -->
<input type="radio" name="tab" id="tab1" checked>
<label for="tab1" class="control">列表 1</label>
<input type="radio" name="tab" id="tab2">
<label for="tab2" class="control">列表 2</label>
<input type="radio" name="tab" id="tab3">
<label for="tab3" class="control">列表 3</label>
<!-- 面板區 -->
<div class="panel" id="panel1">...列表 1 內容...</div>
<div class="panel" id="panel2">...列表 2 內容...</div>
<div class="panel" id="panel3">...列表 3 內容...</div>
</div>
* { box-sizing: border-box; }
li, ul, dd, dl, dt { list-style: none; margin: 0; padding: 0; }
body {
font-family: "Microsoft YaHei", Verdana, sans-serif;
background: url(images/background.jpg) repeat;
height: 100%; width: 100%;
}
.content { margin: 0 auto; width: 1000px; text-align: center; }
/* 隱藏原生 radio */
input[type=radio] {
position: absolute;
z-index: 100;
opacity: 0;
cursor: pointer;
height: 30px; width: 40px;
}
/* 可見控制按鈕 */
.control {
display: inline-block;
margin: 0 -5px;
width: 40px;
background: #eddfc7;
padding: 5px;
border: 1px solid #e0cba0;
cursor: pointer;
vertical-align: bottom;
}
/* 懸停/選中態陰影 */
.control:hover,
input[type=radio]:hover + .control,
input[type=radio]:checked + .control {
box-shadow: inset 0 0 20px #d3b67a;
}
/* 面板預設隱藏 */
.panel { display: none; }
/* 選中對應面板顯示:利用同層級後續兄弟選擇器 */
#tab1:checked ~ #panel1,
#tab2:checked ~ #panel2,
#tab3:checked ~ #panel3 {
display: block;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
input 保持可聚焦,Tab 切換、Space/Enter 選中,天然支援。transition、transform 實現滑動/淡入/縮放切換。name 隔離作用域,可嵌套多層 Tab。| 優點 | 缺點 |
|---|---|
| 零 JS 依賴,極輕量 | HTML 結構耦合(radio 與 panel 需同層) |
| 天然無障礙(鍵盤可操作) | 面板數量固定,動態增減需 JS 配合 |
| 瀏覽器相容性極佳(IE9+) | SEO:隱藏面板內容可能不被索引 |
| 複雜邏輯(如載入更多、分頁)難獨立處理 |