萬盛學電腦網

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

表格鍵盤導航實戰:方向鍵在 input 矩陣中移動焦點、邊界循環、高亮當前行、選中文本

針對純 <table> 結構的輸入矩陣,實現方向鍵移動焦點、進入編輯模式全選文本、邊界循環、當前行高亮、Enter 確認/換行、Esc 取消編輯,純原生 JS、零依賴。

HTML 結構

<table id="data-grid">
  <thead><tr><th>A</th><th>B</th><th>C</th><th>D</th></tr></thead>
  <tbody>
    <tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>
    <tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>
    <tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>
  </tbody>
</table>

TableNavigator 實現

class TableNavigator {
  constructor(table) {
    this.table = table;
    this.inputs = [...table.querySelectorAll('tbody input:not([disabled])')];
    this.cols = table.querySelector('thead').children[0].children.length;
    this.current = null;
    this._bind();
  }

  _bind() {
    this.table.addEventListener('focusin', e => {
      if (e.target.matches('tbody input')) {
        this.current = e.target;
        this._highlightRow(e.target.closest('tr'));
        // 進入編輯模式全選
        if (e.relatedTarget !== e.target) e.target.select();
      }
    });

    this.table.addEventListener('keydown', e => {
      if (!this.current) return;
      const idx = this.inputs.indexOf(this.current);
      if (idx === -1) return;

      let newIdx = idx;
      switch (e.key) {
        case 'ArrowLeft':  newIdx = this._left(idx); break;
        case 'ArrowRight': newIdx = this._right(idx); break;
        case 'ArrowUp':    newIdx = this._up(idx); break;
        case 'ArrowDown':  newIdx = this._down(idx); break;
        case 'Enter':
          e.preventDefault();
          this._moveToNextCell(idx); // Enter 移動到下一單元格
          break;
        case 'Escape':
          this.current.blur(); // 取消編輯
          break;
        case 'Tab': // 保留原生 Tab 行為(瀏覽器自動處理)
          return;
        default: return;
      }
      e.preventDefault();
      this.inputs[newIdx]?.focus();
    });
  }

  _left(idx) { return idx % this.cols === 0 ? idx + this.cols - 1 : idx - 1; }
  _right(idx) { return (idx + 1) % this.cols === 0 ? idx - this.cols + 1 : idx + 1; }
  _up(idx) { return idx < this.cols ? this.inputs.length - this.cols + idx : idx - this.cols; }
  _down(idx) { return idx >= this.inputs.length - this.cols ? idx - this.inputs.length + this.cols : idx + this.cols; }

  _moveToNextCell(idx) {
    const next = (idx + 1) % this.inputs.length;
    this.inputs[next]?.focus();
  }

  _highlightRow(tr) {
    this.table.querySelectorAll('tbody tr').forEach(r => r.classList.remove('active-row'));
    tr?.classList.add('active-row');
  }
}

// CSS
// .active-row { background: #e8f4ff; }
// .active-row input { background: #fff; }

new TableNavigator(document.getElementById('data-grid'));

進階:數據綁定與驗證

// 離開單元格時驗證
table.addEventListener('focusout', e => {
  if (e.target.matches('tbody input')) {
    if (!e.target.checkValidity()) {
      e.target.classList.add('invalid');
      // 可選:阻止焦點離開(需配合焦點管理)
    } else {
      e.target.classList.remove('invalid');
    }
  }
});
copyright © 萬盛學電腦網 all rights reserved