利用 CSS :target 偽類配合錨點鏈接,零 JavaScript 實現文章列表標籤頁切換。右側固定標籤欄,點擊切換左側內容區,當前標籤有箭頭指示。適合靜態頁面、文檔站、無 JS 環境。
id(#a、#b、#c)href="#a" 指向對應面板:target 匹配當前 URL Hash 的元素,設為 display: block,其餘 display: none<style>
dl { position: relative; width: 370px; height: 170px; border: 10px solid #eee; }
dd { margin: 0; width: 370px; height: 170px; overflow: hidden; }
dt { position: absolute; right: 1px; }
ul { margin: 0; padding: 0; width: 390px; height: 170px; list-style: none;
background: url(arrow.gif) no-repeat 75% 20px; border: 1px solid #ccc; }
#b { background-position: 75% center; }
#c { background-position: 75% 86%; }
li { width: 335px; height: 27px; font: 12px/27px sans-serif; white-space: nowrap; overflow: hidden; }
dt a { display: block; margin: 1px; width: 30px; height: 56px; text-align: center;
font: 700 12px/55px sans-serif; color: #fff; text-decoration: none; background: #666; }
dt a:hover { background: orange; }
</style>
<dl>
<dt>
<a href="#a">源碼</a>
<a href="#b">書籍</a>
<a href="#c">軟件</a>
</dt>
<dd>
<ul id="a"><li><a href="...">jQuery 1.3 API 參考手冊 CHM</a></li>...</ul>
<ul id="b"><li><a href="...">《Learning jQuery中文版》 pdf</a></li>...</ul>
<ul id="c"><li><a href="...">《Ajax高級程序設計》電子版</a></li>...</ul>
</dd>
</dl>
dl 相對定位,建立定位上下文dt 絕對定位 right: 1px 固定右側標籤欄ul 疊放在 dd 內,預設全隱藏(或通過 z-index 控制)#a、#b、#c 對應三個面板,背景圖箭頭位置不同指示當前dt a → URL 變 #a → ul#a:target 生效 → 顯示該列表.tab-panels { position: relative; }
.tab-panel { position: absolute; inset: 0; display: none; }
.tab-panel:target { display: block; }
.tab-panel:first-child { display: block; } /* 預設顯示首個 */
/* 標籤樣式 */
.tab-triggers { position: absolute; right: 0; top: 0; display: flex; flex-direction: column; }
.tab-triggers a { padding: 10px 20px; background: #f0f0f0; border: 1px solid #ddd; }
.tab-triggers a:hover { background: #e0e0e0; }
| 優點 | 缺點 |
|---|---|
| 零 JS,極輕量 | URL 會帶上 Hash,影響分享/書籤語意 |
| 瀏覽器前進/後退天然支援 | 無法在切換時執行邏輯(埋點、請求數據) |
| SEO 友好,內容全在 HTML | 大量面板時 DOM 膨脹、首屏渲染慢 |
| 無障礙基礎較好 | 焦點管理需額外 JS 輔助 |
這是 CSS「圖靈完備」的經典證明之一——**狀態機其實早就內建在瀏覽器裡了**。