萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 表格行點擊/懸停高亮:currentActiveRow 變量追蹤當前行狀態

表格行交互高亮是數據展示頁的基礎體驗。本文展示極簡原生 JS 實現:單變量 currentActiveRow 追蹤當前高亮行,onclick/onmouseover 切換背景色,無框架依賴,性能極佳。

核心實現代碼

<script>
var currentActiveRow = null; // 模塊級變量追蹤當前高亮行

function changeActiveRow(rowElement) {
  // 1. 恢復上一行背景
  if (currentActiveRow) {
    currentActiveRow.style.backgroundColor = '';
  }
  
  // 2. 記錄並高亮當前行
  currentActiveRow = rowElement;
  currentActiveRow.style.backgroundColor = '#F2F2F2';
}
</script>

<table>
  <tr onmouseover="changeActiveRow(this)"><td>數據 1</td><td>內容 A</td></tr>
  <tr onmouseover="changeActiveRow(this)"><td>數據 2</td><td>內容 B</td></tr>
  <tr onmouseover="changeActiveRow(this)"><td>數據 3</td><td>內容 C</td></tr>
</table>

事件類型選擇對比

事件觸發時機適用場景體驗差異
onmouseover鼠標進入行瀏覽式數據表、預覽即時反饋,無需點擊
onclick鼠標點擊行選中操作、編輯、詳情明確意圖,狀態持久
onmouseenter鼠標進入(不冒泡)嵌套元素多時避免子元素觸發重複

進階增強:CSS :hover 替代 JS 懸停高亮

<style>
table tr:hover td { background-color: #F2F2F2; } /* 純 CSS,無 JS 開銷 */
table tr.selected td { background-color: #D0E9F6; } /* JS 只管 selected 類 */
</style>

<script>
var currentSelectedRow = null;

function selectRow(row) {
  if (currentSelectedRow) {
    currentSelectedRow.classList.remove('selected');
  }
  row.classList.add('selected');
  currentSelectedRow = row;
}
</script>

<tr onclick="selectRow(this)">...</tr>

優勢:懸停高亮交給 CSS(GPU 加速、無閃爍),JS 僅管理「選中」等業務狀態。

完整功能版:單選/多選/鍵盤導航

var TableSelector = {
  init: function(tableId, options) {
    this.table = document.getElementById(tableId);
    this.mode = options.mode || 'single'; // 'single' | 'multiple'
    this.onSelect = options.onSelect || function() {};
    this.bindEvents();
  },
  
  bindEvents: function() {
    var self = this;
    this.table.querySelectorAll('tbody tr').forEach(function(row) {
      row.addEventListener('click', function(e) {
        self.handleClick(this, e);
      });
    });
    
    // 鍵盤導航
    document.addEventListener('keydown', function(e) {
      if (e.target.closest('table') !== self.table) return;
      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        e.preventDefault();
        self.navigate(e.key === 'ArrowDown' ? 1 : -1);
      }
    });
  },
  
  handleClick: function(row, event) {
    if (this.mode === 'single') {
      this.clearSelection();
      row.classList.add('selected');
      this.lastSelected = row;
    } else {
      if (event.ctrlKey || event.metaKey) {
        row.classList.toggle('selected');
      } else if (event.shiftKey && this.lastSelected) {
        this.rangeSelect(this.lastSelected, row);
      } else {
        this.clearSelection();
        row.classList.add('selected');
      }
      this.lastSelected = row;
    }
    this.onSelect(this.getSelectedRows());
  },
  
  clearSelection: function() {
    this.table.querySelectorAll('tr.selected').forEach(function(r) {
      r.classList.remove('selected');
    });
  },
  
  getSelectedRows: function() {
    return Array.from(this.table.querySelectorAll('tr.selected'));
  },
  
  navigate: function(direction) {
    var rows = Array.from(this.table.querySelectorAll('tbody tr'));
    var current = this.table.querySelector('tbody tr.selected') || rows[0];
    var idx = rows.indexOf(current);
    var next = rows[idx + direction];
    if (next) next.click();
  }
};

// 使用
TableSelector.init('dataTable', { mode: 'multiple', onSelect: function(rows) {
  console.log('選中', rows.length, '行');
}});

現代 CSS 方案::has() 偽類(未來標準)

/* 當行有 .selected 類時高亮 */
tr:has(.selected) td { background: #D0E9F6; }

/* 或配合 input:checked */
tr:has(input:checked) td { background: #D0E9F6; }

總結

簡單懸停高亮用 CSS :hover;點擊選中狀態管理用 JS 變量追蹤 currentActiveRow;複雜選交互封裝組件支援單選/多選/範圍選/鍵盤導航。關注點分離:CSS 管樣式,JS 管狀態。

copyright © 萬盛學電腦網 all rights reserved