萬盛學電腦網

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

JavaScript 控制表格奇偶行樣式:CSS 與 JS 方案對比

方案一:CSS 偽類選擇器(推薦,零 JS)


/* 現代瀏覽器完美支援 */
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 開銷、自動適應動態增減行、打印樣式可控

方案二:jQuery 簡潔版


// 頁面加載後執行一次
$(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');
}

方案三:原生 JS 實現(無依賴)


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'); // 重新條紋
}

方案四:CSS 變量主題化(進階)


: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 變量主題⭐⭐⭐⭐⭐✅ 自動⭐⭐⭐⭐多主題/暗黑模式

無障礙建議

  • 確保對比度達到 WCAG AA 級(4.5:1)
  • 不僅依賴顏色區分,可添加邊框或圖標
  • 3. 提供「高對比度」切換開關
copyright © 萬盛學電腦網 all rights reserved