萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

JavaScript 動態操控 CSS 實現表格隔行換色 (傳統方案與現代替代)

傳統 JS 方案 (教學參考)

function stripeTables() {
  if (!document.getElementsByTagName) return;
  var tables = document.getElementsByTagName("table");
  for (var i = 0; i < tables.length; i++) {
    var rows = tables[i].getElementsByTagName("tr");
    for (var j = 0; j < rows.length; j++) {
      if (j % 2 === 0) {
        rows[j].style.backgroundColor = "#f9f9f9"; // 奇數行 (0-index)
      } else {
        rows[j].style.backgroundColor = "#fff";
      }
    }
  }
}
window.onload = stripeTables;

缺點分析

  • 行內樣式優先級高,後續 CSS :nth-child 難以覆蓋 (需 !important)
  • 動態內容 (AJAX 新增行、排序、分頁) 需手動重新呼叫
  • 效能:大量表格逐行設定 style 觸發重繪
  • 維護:顏色寫死在 JS,設計變更需改代碼

現代最佳方案:純 CSS :nth-child

/* CSS 檔案 */
#data-table tbody tr:nth-child(odd)  { background:#f9f9f9; }
#data-table tbody tr:nth-child(even) { background:#fff; }
  • 零 JS、自動應用動態新增行、瀏覽器原生優化、易維護
  • 支援:IE9+、所有現代瀏覽器

漸進增強:CSS 為主,JS 兜底 IE8

<!--[if lte IE 8]>
<script>
  // 僅 IE8 執行
  function stripeIE8() { ... }
  window.onload = stripeIE8;
</script>
<![endif]-->

進階:資料屬性驅動 (配合 JS 框架)

<tr data-row-index="0">...</tr>
<tr data-row-index="1">...</tr>

/* CSS */
tr[data-row-index] { --row: attr(data-row-index); } /* 無法直接用 attr 於數學運算 */

實務上:Vue/React 直接在渲染時綁定 :class="{odd: index%2===0}",或用 CSS :nth-child 完全脫離 JS。

完整 HTML 範例 (含表頭不變色)

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>表格斑馬紋</title>
<style>
table { border-collapse:collapse; width:100%; }
th, td { border:1px solid #ddd; padding:.5rem; }
tbody tr:nth-child(odd) { background:#f5f5f5; }
tbody tr:hover { background:#e3f2fd; } /* 滑鼠懸停高亮優先 */
</style></head><body>
<table id="data-table">
  <thead><tr><th>姓名</th><th>城市</th></tr></thead>
  <tbody>
    <tr><td>張三</td><td>台北</td></tr>
    <tr><td>李四</td><td>台中</td></tr>
    <tr><td>王五</td><td>高雄</td></tr>
  </tbody>
</table>
</body></html>

總結

**現代專案請直接用 CSS :nth-child**,只有維護極舊 IE8 專案才需 JS 兜底,並以條件編譯隔離。將樣式邏輯留在 CSS、行為邏輯留在 JS,關注點分離、可維護性最高。

copyright © 萬盛學電腦網 all rights reserved