function SetTableColor() {
var tbl = document.getElementById("tblMain");
var trs = tbl.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
var j = i + 1; // 轉為 1-based 索引
trs[i].style.background = (j % 2 === 0) ? "yellow" : "blue";
}
}
<table id="tblMain" border="1">
<tr><td>1</td><td>三星</td><td>AA</td></tr>
<tr><td>2</td><td>Norkia</td><td>BB</td></tr>
<tr><td>3</td><td>蘋果</td><td>CC</td></tr>
...
</table>
<body onload="SetTableColor()">
getElementsByTagName("tr") 獲取所有行(包含 thead/tbody/tfoot 中的行)。i 從 0 開始,i+1 轉為自然行號判斷奇偶。style.background 設置內聯樣式,覆蓋 CSS。<style>
#tblMain tbody tr:nth-child(odd) { background: blue; }
#tblMain tbody tr:nth-child(even) { background: yellow; }
/* 或 */
#tblMain tbody tr:nth-child(2n) { background: yellow; }
#tblMain tbody tr:nth-child(2n-1) { background: blue; }
</style>
優勢:無 JS 依賴、不干擾內聯樣式優先級、動態增删行自動生效、打印樣式可控、性能最優。
function stripeTable(tableId) {
const table = document.getElementById(tableId);
const rows = table.querySelectorAll('tbody tr'); // 僅 tbody 數據行
rows.forEach((row, i) => {
row.style.backgroundColor = i % 2 === 0 ? '#eef' : '#fee';
});
}
// 動態新增行後調用
function addRow(data) {
const table = document.getElementById('tblMain');
const tbody = table.tBodies[0];
const tr = tbody.insertRow(-1);
data.forEach(text => {
const td = tr.insertCell(-1);
td.textContent = text;
});
stripeTable('tblMain'); // 重新條紋
}