< HTML >
< HEAD >
< TITLE ></ TITLE >
< script language = " javascript " >
// /
//
// 功能:這個類使得被附加的表格可以支援行點選高亮
// 參數:
// tbl: 要附加樣式的 table.
// selectedRowIndex: 初始高亮的行的索引(從 0 開始). 此參數可省。
// hilightColor: 高亮顔色。可省(預設為綠色)
//
// Author: Neil Chen
// Date: 2005-09-05
//
// /
function TableRowHilighter(tbl, selectedRowIndex, hilightColor) {
this .currentRow = null ;
this .hilightColor = hilightColor ? hilightColor : 'green';
if (selectedRowIndex != null
&& selectedRowIndex >= 0
&& selectedRowIndex < tbl.rows.length)
{
this .currentRow = tbl.rows[selectedRowIndex];
tbl.rows[selectedRowIndex].runtimeStyle.backgroundColor = this .hilightColor;
}
var _this = this ;
tbl.attachEvent( " onclick " , table_onclick);
function table_onclick() {
var e = event.srcElement;
if (e.tagName == 'TD')
e = e.parentElement;
if (e.tagName != 'TR') return ;
if (e == _this.currentRow) return ;
if (_this.currentRow)
_this.currentRow.runtimeStyle.backgroundColor = '';
e.runtimeStyle.backgroundColor = _this.hilightColor;
_this.currentRow = e;
}
}
</ script >
</ HEAD >
< BODY >
< table id = " table1 " border = " 1 " cellspacing = " 0 " cellpadding = " 5 " >
< tr >
< td onclick = " alert('a'); " > a </ td >
< td > b </ td >
< td > c </ td >
</ tr >
< tr >
< td > d </ td >
< td > e </ td >
< td > f </ td >
</ tr >
< tr >
< td > g </ td >
< td > h </ td >
< td > i </ td >
</ tr >
</ table >
< br >
< table id = " table2 " border = " 1 " cellspacing = " 0 " cellpadding = " 5 " >
< tr >
< td > a </ td >
< td > b </ td >
< td > c </ td >
</ tr >
< tr >
< td > d </ td >
< td > e </ td >
< td > f </ td >
</ tr >
< tr >
< td > g </ td >
< td > h </ td >
< td > i </ td >
</ tr >
</ table >
< br >
< table id = " table3 " border = " 1 " cellspacing = " 0 " cellpadding = " 5 " >
< tr >
< td > a </ td >
< td > b </ td >
< td > c </ td >
</ tr >
< tr >
< td > d </ td >
< td > e </ td >
< td > f </ td >
</ tr >
< tr >
< td > g </ td >
< td > h </ td >
< td > i </ td >
</ tr >
</ table >
</ BODY >
< script >
// 調用範例
var hilighter1 = new TableRowHilighter(document.getElementById('table1'), 1 , 'yellow');
var hilighter2 = new TableRowHilighter(document.getElementById('table2'), 0 , 'lightsteelblue');
var hilighter3 = new TableRowHilighter(document.getElementById('table3'), 2 );
</ script >
</ HTML >
其中行點選的事件處理用的是 attachEvent 方法,是以不支援 IE 5.5 以下的浏覽器,以及非 IE 浏覽器。但有一個好處就是該高亮功能不影響 HTML 元素中原有的 onclick 事件處理邏輯。