資料表格若能做到隔行變色、滑鼠移入高亮、點擊選取整列,可讀性會大幅提升。以下用純 jQuery 實作,效果比單純換色更完整。
<html>
<head>
<style type="text/css">
.table-tr-title{
height: 26px;
font-size: 12px;
text-align: center;
}
.table-tr-content{
height: 18px;
background: #FFFFFF;
text-align: center;
font-size: 12px;
}
.normalEvenTD{
background: #DFD8D8;
}
.normalOddTD{
background: #FFFFFF;
}
.hoverTD{
background-color: #eafcd5;
height: 18px;
text-align: center;
font-size: 12px;
}
.trSelected{
background-color: #51b2f6;
height: 18px;
text-align: center;
font-size: 12px;
}
</style>
</head>
<body>
<table width="99%" class="list" style="word-break: break-all" border="0"
align="center" cellpadding="0" cellspacing="1" bgcolor="#c0de98">
<tr class="table-tr-title">
<td width="5%">標題</td>
<td width="5%">標題</td>
<td width="5%">標題</td>
<td width="5%">標題</td>
</tr>
<tr class="table-tr-content">
<td width="5%">數據</td>
<td width="5%">數據</td>
<td width="5%">數據</td>
<td width="5%">數據</td>
</tr>
<!-- 其餘資料列結構相同,此處省略 -->
</body>
</html>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script>
$(function(){
/////// datagrid 選取列變色與滑鼠經過列變色 ///////
var dtSelector = ".list";
var tbList = $(dtSelector);
tbList.each(function() {
var self = this;
$("tr:even:not(:first)", $(self)).addClass("normalEvenTD"); // 標頭下一列起的奇數列(1,3,5...)
$("tr:odd", $(self)).addClass("normalOddTD"); // 標頭下一列起的偶數列(2,4,6...)
// 滑鼠經過的列變色
$("tr:not(:first)", $(self)).hover(
function () { $(this).addClass('hoverTD'); $(this).removeClass('table-td-content'); },
function () { $(this).removeClass('hoverTD'); $(this).addClass('table-td-content'); }
);
// 選取列變色
$("tr", $(self)).click(function (){
var trThis = this;
$(self).find(".trSelected").removeClass('trSelected');
if ($(trThis).get(0) == $("tr:first", $(self)).get(0)){
return;
}
$(trThis).addClass('trSelected');
});
});
});
</script>
效果顯示:

跳過標頭列:not(:first) 與 tr:first 的比對,確保點擊標題列不會被當成選取資料列。
先清除再套用:點擊時先 removeClass('trSelected') 再 addClass,保證任何時刻只有一列被選取,這比用旗標判斷簡潔得多。
hover 的雙函式:hover(fn1, fn2) 分別對應移入與移出,比 jQuery 3 建議的 mouseenter/mouseleave 更省字。
:nth-child 的 CSS 偽類取代 JS 加上下底色,可以少跑一層迴圈:tr:nth-child(even){ background:#DFD8D8; }$(".list").on("click", "tr", handler),避免綁定大量事件造成效能低落。table-td-content 並未在樣式中定義,這段可移除;若目的是保留原本的隔行底色,改用 CSS 的 tr:hover 會更乾淨。