table tr:nth-child(even) { background: #f2f2f2; }
table tr:nth-child(odd) { background: #fff; }
/* 或 */
table tr:nth-child(2n) { background: #f2f2f2; }
優點:無 JS 依賴、效能佳、支援動態增減行(配合 CSS 即時生效)。
function stripeTables() {
if (!document.getElementsByTagName) return;
const tables = document.getElementsByTagName('table');
for (let i = 0; i < tables.length; i++) {
let odd = false;
const rows = tables[i].getElementsByTagName('tr');
for (let j = 0; j < rows.length; j++) {
rows[j].style.backgroundColor = odd ? '#ccc' : '';
odd = !odd;
}
}
}
window.onload = stripeTables;
缺點:需等 DOM 載入、動態新增行需手動觸發、污染內聯樣式。
.data-table tr:nth-child(even) { background: #eef; }
.data-table tr:hover { background: #ffd; } /* 滑鼠懸停高亮 */
現代專案**直接使用 :nth-child()**,簡潔高效。僅在必須支援 IE8 且無法引入 Polyfill 時,才考慮 JS 方案。