在製作數據表格時,經常需要讓鼠標移過某一行時高亮該行,以提升可讀性。原理很簡單:為每個 <tr> 綁定 onmousemove 事件,觸發時先清除所有行的背景色,再將當前行設為目標顏色。
示例代碼如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>鼠標經過給tr換顏色</title>
</head>
<body>
<table align="center" width="100%" border="1" cellspacing="1" cellpadding="1" >
<tr style="cursor:hand " onmousemove="changeTrColor(this)">
<td align="center">1</td>
<td height="20"> 123</td>
<td height="20"> abvx</td>
<td height="20"> 465465</td>
<td height="20">546654654</td>
</tr>
<tr style="cursor:hand " onmousemove="changeTrColor(this)">
<td align="center">1</td>
<td height="20"> 123</td>
<td height="20"> abvx</td>
<td height="20"> 465465</td>
<td height="20">546654654</td>
</tr>
<tr style="cursor:hand " onmousemove="changeTrColor(this)">
<td align="center">1</td>
<td height="20"> 123</td>
<td height="20"> abvx</td>
<td height="20"> 465465</td>
<td height="20">546654654</td>
</tr>
</table>
<script type="text/javascript">
function changeTrColor(obj){
var _table=obj.parentNode;
for (var i=0;i<_table.rows.length;i++){
_table.rows[i].style.backgroundColor="";
}
obj.style.backgroundColor="blue";
}
</script>
</body>
</html>
程式要點:changeTrColor 先透過 obj.parentNode 取得整個表格,迴圈把每一行的背景色重設為空,再將觸發事件的當前行設為藍色,藉此達到「只有滑鼠所在行高亮」的效果。若偏好其他配色,只需替換 "blue" 這個值即可。