/* 現代瀏覽器完美支援 */
table tr:nth-child(odd) { background: #f9f9f9; }
table tr:nth-child(even) { background: #fff; }
/* 懸停高亮優先級更高 */
table tr:hover { background: #e3f2fd !important; }
/* 表頭不參與 */
table thead tr { background: #333; color: #fff; }
table thead tr:nth-child(odd) { background: #333; } /* 重置 */
✅ 無 JS 開銷、自動適應動態增減行、打印樣式可控
// 頁面加載後執行一次
$(function() {
$('table tbody tr:odd').addClass('odd-row');
$('table tbody tr:even').addClass('even-row');
});
// 動態添加行後調用
function refreshRowStriping(tableSelector) {
$(tableSelector + ' tbody tr').removeClass('odd-row even-row')
.filter(':odd').addClass('odd-row').end()
.filter(':even').addClass('even-row');
}
function stripeTable(tableId) {
const table = document.getElementById(tableId);
if (!table) return;
const tbody = table.querySelector('tbody') || table;
const rows = tbody.querySelectorAll('tr');
rows.forEach((row, index) => {
row.classList.toggle('odd-row', index % 2 === 0); // 0-based: 奇數行
row.classList.toggle('even-row', index % 2 === 1); // 偶數行
});
}
// 初始化
document.addEventListener('DOMContentLoaded', () => stripeTable('dataTable'));
// 動態新增行後調用
function addRow(data) {
const tbody = document.querySelector('#dataTable tbody');
const row = tbody.insertRow();
// 填充單元格...
stripeTable('dataTable'); // 重新條紋
}
:root {
--stripe-odd: #f9f9f9;
--stripe-even: #ffffff;
--stripe-hover: #e3f2fd;
}
table.striped tbody tr:nth-child(odd) { background: var(--stripe-odd); }
table.striped tbody tr:nth-child(even) { background: var(--stripe-even); }
table.striped tbody tr:hover { background: var(--stripe-hover); }
/* 暗黑模式自動適配 */
@media (prefers-color-scheme: dark) {
:root {
--stripe-odd: #1e1e1e;
--stripe-even: #252525;
--stripe-hover: #333;
}
}
// 需求:按分組字段分組,組內奇偶行著色
function stripeByGroup(tableSelector, groupCellIndex = 0) {
const rows = document.querySelectorAll(tableSelector + ' tbody tr');
let groupValue = null;
let groupIndex = 0;
rows.forEach(row => {
const cellValue = row.cells[groupCellIndex]?.textContent?.trim();
if (cellValue !== groupValue) {
groupValue = cellValue;
groupIndex = 0;
}
row.classList.toggle('odd-row', groupIndex % 2 === 0);
row.classList.toggle('even-row', groupIndex % 2 === 1);
groupIndex++;
});
}
| 方案 | 性能 | 動態行 | 維護性 | 適用場景 |
|---|---|---|---|---|
| CSS nth-child | ⭐⭐⭐⭐⭐ | ✅ 自動 | ⭐⭐⭐⭐⭐ | 所有現代項目 |
| jQuery | ⭐⭐⭐ | 需手動刷新 | ⭐⭐⭐⭐ | 舊項目維護 |
| 原生 JS | ⭐⭐⭐⭐ | 需手動刷新 | ⭐⭐⭐⭐ | 無依賴項目 |
| CSS 變量主題 | ⭐⭐⭐⭐⭐ | ✅ 自動 | ⭐⭐⭐⭐ | 多主題/暗黑模式 |