jQuery 提供 `:even` (索引 0,2,4...) 與 `:odd` (索引 1,3,5...) 偽類選取器,配合 `addClass()` 即可輕鬆實現斑馬紋表格。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>表格隔行換色</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("#stu tr:even").addClass("bg"); // 偶數列 (含表頭第0列)
$("#stu tr:odd").addClass("bg1"); // 奇數列
});
</script>
<style>
#stu { width: 300px; border: solid 1px green; border-collapse: collapse; border-spacing: 0; }
#stu th { background: #ccc; padding: 8px; }
#stu td { padding: 8px; }
.bg { background: #e8f4fd; } // 淺藍
.bg1 { background: #fff9e6; } // 淺黃
</style>
</head>
<body>
<table id="stu">
<tr><th>學號</th><th>姓名</th><th>專業</th></tr>
<tr><td>0812124</td><td>羊羊羊</td><td>生物工程</td></tr>
<tr><td>0812120</td><td>燕燕燕</td><td>軟件工程</td></tr>
<tr><td>0812124</td><td>王美人</td><td>計算機</td></tr>
<tr><td>0812124</td><td>海飛絲</td><td>商務英語</td></tr>
<tr><td>0812124</td><td>宋夫人</td><td>藥物研究</td></tr>
</table>
</body>
</html>
上面範例中,`
$("#stu tbody tr:even").addClass("bg");
$("#stu tbody tr:odd").addClass("bg1");
$("#stu tr:gt(0):even").addClass("bg");
$("#stu tr:gt(0):odd").addClass("bg1");
/* 現代瀏覽器全支援,含 IE9+ */
#stu tbody tr:nth-child(odd) { background: #e8f4fd; }
#stu tbody tr:nth-child(even) { background: #fff9e6; }
當表格列動態新增/刪除/排序後,需重新套用:
function refreshStriping(tableId) {
var $table = $("#" + tableId);
$table.find("tbody tr").removeClass("bg bg1");
$table.find("tbody tr:even").addClass("bg");
$table.find("tbody tr:odd").addClass("bg1");
}
// 新增列後呼叫
function addRow(data) {
$("#stu tbody").append("" + data.join(" ") + " ");
refreshStriping("stu");
}
| 方案 | 效能 | 維護性 | 動態更新 |
|---|---|---|---|
| jQuery :even/:odd | 中 (需遍歷 DOM) | 好 | 需手動 refresh |
| CSS nth-child | 極佳 (瀏覽器原生) | 極好 (純樣式) | 自動生效 ✓ |
| CSS :nth-of-type | 極佳 | 好 | 自動生效 ✓ |