後台管理、數據錄入、電子表格常需鍵盤在二維網格間移動焦點。本文實現一個通用 GridNavigator:自動發現可聚焦元素、建立座標映射、支援不規則網格、邊界循環/停止模式、動態行列增減、螢幕閱讀器友好。
<div class="grid-container" role="grid" aria-label="數據錄入表格">
<div role="row">
<input role="gridcell" type="text" data-pos="0,0">
<input role="gridcell" type="text" data-pos="0,1">
<input role="gridcell" type="text" data-pos="0,2">
</div>
<div role="row">
<input role="gridcell" type="text" data-pos="1,0">
<input role="gridcell" type="text" data-pos="1,1">
<select role="gridcell" data-pos="1,2"><option>A</option></select>
</div>
</div>
class GridNavigator {
constructor(container, options = {}) {
this.container = container;
this.wrap = options.wrap ?? true; // 邊界循環
this.selector = options.selector || '[role="gridcell"]:not([disabled]), [role="gridcell"] [tabindex]:not([tabindex="-1"])';
this.cells = [];
this.posMap = new Map(); // 'r,c' -> cell
this.current = null;
this._scan();
this._bind();
}
_scan() {
this.cells = [...this.container.querySelectorAll(this.selector)];
this.posMap.clear();
this.cells.forEach((cell, i) => {
const pos = cell.dataset.pos || `${Math.floor(i/10)},${i%10}`; // 兜底
this.posMap.set(pos, cell);
cell._gridPos = pos;
});
// 建立行列索引
this.rows = new Map();
this.cols = new Map();
this.cells.forEach(cell => {
const [r, c] = cell._gridPos.split(',').map(Number);
if (!this.rows.has(r)) this.rows.set(r, []);
this.rows.get(r).push(cell);
if (!this.cols.has(c)) this.cols.set(c, []);
this.cols.get(c).push(cell);
});
this.rowKeys = [...this.rows.keys()].sort((a,b)=>a-b);
this.colKeys = [...this.cols.keys()].sort((a,b)=>a-b);
}
_bind() {
this.container.addEventListener('keydown', e => {
if (!this.current) return;
const [r, c] = this.current._gridPos.split(',').map(Number);
let nr = r, nc = c;
switch (e.key) {
case 'ArrowUp': nr = this._prevRow(r); break;
case 'ArrowDown': nr = this._nextRow(r); break;
case 'ArrowLeft': nc = this._prevCol(c); break;
case 'ArrowRight': nc = this._nextCol(c); break;
case 'Home': nc = this.colKeys[0]; break;
case 'End': nc = this.colKeys[this.colKeys.length-1]; break;
default: return;
}
e.preventDefault();
this._focus(nr, nc);
});
// 焦點進入自動更新 current
this.container.addEventListener('focusin', e => {
if (e.target.matches(this.selector)) this.current = e.target;
});
}
_prevRow(r) { const i = this.rowKeys.indexOf(r); return this.wrap && i===0 ? this.rowKeys[this.rowKeys.length-1] : this.rowKeys[Math.max(0,i-1)]; }
_nextRow(r) { const i = this.rowKeys.indexOf(r); return this.wrap && i===this.rowKeys.length-1 ? this.rowKeys[0] : this.rowKeys[Math.min(this.rowKeys.length-1,i+1)]; }
_prevCol(c) { const i = this.colKeys.indexOf(c); return this.wrap && i===0 ? this.colKeys[this.colKeys.length-1] : this.colKeys[Math.max(0,i-1)]; }
_nextCol(c) { const i = this.colKeys.indexOf(c); return this.wrap && i===this.colKeys.length-1 ? this.colKeys[0] : this.colKeys[Math.min(this.colKeys.length-1,i+1)]; }
_focus(r, c) {
const cell = this.posMap.get(`${r},${c}`);
if (cell) { cell.focus(); this.current = cell; }
else {
// 目標位置無可聚焦元素,尋找同行/同列最近
const rowCells = this.rows.get(r) || [];
const colCells = this.cols.get(c) || [];
const target = rowCells[0] || colCells[0];
if (target) { target.focus(); this.current = target; }
}
}
// 公開方法:動態更新
refresh() { this._scan(); }
}
// 初始化
new GridNavigator(document.querySelector('[role="grid"]'));
function addRow(gridNav, rowIndex, cellsHTML) {
const row = document.createElement('div');
row.role = 'row';
row.innerHTML = cellsHTML;
const container = gridNav.container;
const refRow = container.querySelectorAll('[role="row"]')[rowIndex] || null;
container.insertBefore(row, refRow);
gridNav.refresh();
}
role="grid",行 role="row",單元格 role="gridcell"。<input>、<select> 等原生控件,自帶語意。<div role="gridcell" tabindex="0"> 使其可聚焦。