萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現表格隔行變色:奇偶行樣式交替

核心代碼

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";
    }
}

HTML 結構

<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()">

關鍵點

  1. getElementsByTagName("tr") 獲取所有行(包含 thead/tbody/tfoot 中的行)。
  2. 索引 i 從 0 開始,i+1 轉為自然行號判斷奇偶。
  3. 直接操作 style.background 設置內聯樣式,覆蓋 CSS。

現代最佳實踐:純 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 依賴、不干擾內聯樣式優先級、動態增删行自動生效、打印樣式可控、性能最優。

JS 方案優化(若必須用 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'); // 重新條紋
}
copyright © 萬盛學電腦網 all rights reserved