表格是資料呈現的主力,而「隔行變色、移入高亮、點擊選取」這三件事合起來,能大幅改善閱讀體驗。這個練習同時示範了狀態管理的重要性。
i % 2:任何整數除以 2 的餘數只有 0 和 1 兩種,正好對應兩種底色,這就是隔行變色最經典的作法。
tr.onoff = 1:替每一行掛一個自訂狀態旗標。滑鼠移入移出時先檢查它——若該行已被點擊選取(onoff 為 0),就不要讓 hover 效果覆蓋掉選取狀態。少了這個旗標,滑過已選取的行就會「掉色」。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title>表格互動效果</title>
<style>
table { border-collapse:collapse }
table td {
height:26px; font-size:12px; color:#333; border:1px solid #09c;
text-align:center; padding:0 10px;
}
</style>
</head>
<body>
<script>
window.onload = function () {
var tables = document.getElementById("tables");
var tables_li = tables.getElementsByTagName("tr");
var i, len = tables_li.length;
for (i = 0; i < len; i++) {
tables_li[i].onoff = 1;
tables_li[i].index = i;
tables_li[i].style.backgroundColor = i % 2 ? "#ace" : "";
tables_li[i].onmouseover = function () {
if (this.onoff == 1) {
this.style.backgroundColor = "#06c";
}
};
tables_li[i].onmouseout = function () {
if (this.onoff == 1) {
this.style.backgroundColor = this.index % 2 ? "#ace" : "";
}
};
tables_li[i].onclick = function () {
if (this.onoff == 1) {
this.onoff = 0;
this.style.backgroundColor = "#069";
} else {
this.onoff = 1;
this.style.backgroundColor = this.index % 2 ? "#ace" : "";
}
};
}
};
</script>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0" id="tables">
<tr><td>1</td><td>內容內容</td></tr>
<tr><td>2</td><td>內容內容</td></tr>
<tr><td>3</td><td>內容內容</td></tr>
<tr><td>4</td><td>內容內容</td></tr>
<tr><td>5</td><td>內容內容</td></tr>
<tr><td>6</td><td>內容內容</td></tr>
<tr><td>7</td><td>內容內容</td></tr>
<tr><td>8</td><td>內容內容</td></tr>
<tr><td>9</td><td>內容內容</td></tr>
<tr><td>10</td><td>內容內容</td></tr>
</table>
</body>
</html>
Modern CSS 已經有 tr:nth-child(even) 可以直接處理隔行變色,tr:hover 能取代移入移出,.selected class 則比 onoff 數字旗標更好讀。這個範例的價值在於它把所有狀態都攤在眼前——理解「三種狀態(常態/hover/選取)會互相打架,必須有旗標仲裁」這件事,比記住 API 更重要。