萬盛學電腦網

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

表格隔行換色實作:CSS nth-child 純樣式方案與 JavaScript 兼容舊瀏覽器做法

現代純 CSS 方案(推薦)

table tr:nth-child(even) { background: #f2f2f2; }
table tr:nth-child(odd)  { background: #fff; }
/* 或 */
table tr:nth-child(2n) { background: #f2f2f2; }

優點:無 JS 依賴、效能佳、支援動態增減行(配合 CSS 即時生效)。

傳統 JavaScript 方案(IE8- 相容)

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 方案。

copyright © 萬盛學電腦網 all rights reserved