DIV CSS 佈局教程網

JavaScript 實現點擊表格單元格高亮(改變背景色)
編輯:關於JavaScript     

數據表格常需要「選中行/選中列」的視覺反饋,比如點擊表頭切換當前展示的列表。實現的核心是事件委托:在 table 上綁一次點擊事件,通過 event.target 判斷點到的是不是 TD,再定位到所在列做樣式切換。

完整代碼

<html>
<body>
<table onclick="SetColor(event)" id="_t" width="500" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="93" height="29" background="hotlinkbg.gif" align="center">出租信息</td>
    <td width="93" height="29" background="hotlinkbg.gif" align="center">求租信息</td>
    <td width="314" height="29" background="hotlinkbg.gif"></td>
  </tr>
</table>

<table width="500">
  <tr>
    <td>aaaaa</td>
    <td>bbbbb</td>
    <td>ccccc</td>
    <td>ddddd</td>
  </tr>
</table>

<script type="text/javascript">
var oldClr = new Array();

function SetColor(e) {
  if (!e) e = window.event;
  var obj;
  if (window.event) obj = e.srcElement; else obj = e.target;
  if (obj.tagName != "TD") return;

  var oldTD = obj;
  // 向上找到所在的 TR
  while (obj.tagName != "TR") obj = obj.parentNode;

  // 計算被點擊單元格在行內的列索引
  var i;
  for (i = 0; i < obj.cells.length; i++) {
    if (obj.cells[i] == oldTD) break;
  }

  var table = document.getElementById("_t");
  for (var j = 0; j < table.rows.length; j++) {
    // 如需清除其它列的背景,打開下面三行
    for (var m = 0; m < table.rows[j].cells.length; m++) {
      table.rows[j].cells[m].background = oldClr[m];
    }
    // 同一列做高亮/還原的切換
    table.rows[j].cells[i].background =
      table.rows[j].cells[i].background == oldClr[i] ? "button1_on.gif" : oldClr[i];
  }
}

// 初始化記錄每列原始背景
window.onload = function () {
  var table = document.getElementById("_t");
  for (var j = 0; j < table.rows[0].cells.length; j++) {
    oldClr[j] = table.rows[0].cells[j].background;
  }
};
</script>
</body>
</html>

代碼要點說明

第一,兼容事件源。老一點的 IE 用 srcElement,標準瀏覽器用 target,兩者都取一遍最穩妥。

第二,列索引的計算方式。先記住被點擊的 TD,再向上找到 TR,然後遍歷 tr.cells 找到匹配項的下標,這個下標就是列號。

第三,用 oldClr 數組緩存初始背景,才能實現「再次點擊還原」的切換效果。如果直接用固定值覆蓋,原始樣式就丟了。

第四,現代項目更推薦用 class 切換代替直接改 background 屬性:cell.classList.toggle('active'),樣式與行為分離,維護成本更低;同時把 onclick 內聯屬性改成 addEventListener 綁定,也能避免多個腳本互相覆蓋。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved