表格資料一多,橫向閱讀就容易串行。隔行換色(斑馬紋)是最經典也最省成本的改善方式。用 jQuery 來做這件事非常輕量,核心只需要兩個選擇器: :even 與 :odd。
$(function(){
$("#stu tr:even").addClass("bg");
$("#stu tr:odd").addClass("bg1");
});
搭配最簡陋的樣式定義:
#stu{width:300px;border:solid 1px green;border-spacing:0px;}
#stu th{background:#ccc;}
.bg{background:blue;}
.bg1{background:yellow;}
表格內容則是一份學生名單,資料列包在 <table id="stu"> 之中即可。執行後,偶數列與奇數列會自動套上不同底色。
jQuery 的 :even/:odd 屬於擴充選擇器,並非標準 CSS 語法,它需要先取得全部元素再逐一過濾,資料量大時效能不如原生方案。因此正式專案裡常見兩種替代寫法:
$("#stu tbody tr:nth-child(odd)").addClass("bg");
$("#stu tbody tr:nth-child(even)").addClass("bg1");
:nth-child 是 jQuery 支援的標準 CSS 選擇器,內部可直接交給瀏覽器的 querySelectorAll 處理,速度更快。
tbody tr:nth-child(odd){ background:#eef; }
tbody tr:nth-child(even){ background:#ffe; }
純 CSS 方案完全不需要 JavaScript,也不受資料量影響,是最省資源的選擇。
使用這類選擇器時,最好把資料列包進 <tbody>,並避免把 <th> 的表頭列算進去,否則配色會整體錯位一格。另外,如果表格是透過 AJAX 動態插入的,記得在資料渲染完成後再呼叫一次上色函式。
總的來說,用 jQuery 做隔行換色確實簡單明瞭,適合快速原型;而 production 環境則建議優先考慮純 CSS 的 nth-child。