在資料錄入密集型系統 (ERP、POS、倉管、實驗室記錄) 中,使用者習慣用數字鍵盤的 Enter 鍵在欄位間移動,而非 Tab。本文實現一個通用的「Enter 即 Tab」指令,支援動態表單、巢狀結構、跳過不可見/禁用元素,並解決事件冒泡、預設行為阻止等細節問題。
input、select、textarea、button)type="hidden"、disabled、readonly、display:none、type="button/submit/reset" (視需求)// enter-as-tab.js
const FOCUSABLE_SELECTOR = `
input:not([type="hidden"]):not([disabled]):not([readonly]),
select:not([disabled]),
textarea:not([disabled]):not([readonly]),
button:not([disabled]),
[tabindex]:not([tabindex="-1"])
`;
function getFocusableElements(container = document) {
return Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR))
.filter(el => el.offsetParent !== null); // 過濾 display:none
}
function handleEnterAsTab(event) {
if (event.key !== 'Enter' && event.keyCode !== 13) return;
// 允許 textarea 內換行 (Shift+Enter 或單獨配置)
if (event.target.tagName === 'TEXTAREA' && !event.shiftKey) return;
// 允許表單提交 (在 submit 按鈕上)
if (event.target.matches('button[type="submit"], input[type="submit"]')) return;
event.preventDefault(); // 防止表單提交、換行等預設行為
event.stopPropagation(); // 避免觸發父層監聽
const focusables = getFocusableElements(event.target.form || document);
const currentIndex = focusables.indexOf(event.target);
if (currentIndex === -1) return; // 目標不在可聚焦列表 (罕見)
const nextIndex = (currentIndex + 1) % focusables.length; // 循環
focusables[nextIndex].focus();
focusables[nextIndex].select?.(); // 可選:全選文字方便覆寫
}
// 掛載:表單層級 (推薦,隔離範圍)
export function enableEnterAsTab(formSelector = 'form') {
document.querySelectorAll(formSelector).forEach(form => {
form.addEventListener('keydown', handleEnterAsTab);
});
}
// 或全域掛載 (簡單專案)
document.addEventListener('keydown', handleEnterAsTab);
// 原文邏輯改良版:支援動態元素、正確選擇器
$(document).on('keydown', 'input[type="text"], input[type="password"], textarea, select', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
// 獲取同表單內所有可聚焦元素 (含動態新增)
const $focusables = $(this.form || document).find(
'input:not([type="hidden"]):not([disabled]):not([readonly]), ' +
'select:not([disabled]), ' +
'textarea:not([disabled]):not([readonly]), ' +
'button:not([disabled])'
).filter(':visible');
const idx = $focusables.index(this);
if (idx >= 0) {
const next = $focusables[(idx + 1) % $focusables.length];
next.focus();
if (next.select) next.select();
}
}
});
<form id="dataEntry">
<fieldset>
<legend>化工數據錄入</legend>
<div class="field">
<label>溫度</label>
<input type="number" name="temp" step="0.1" />
</div>
<div class="field">
<label>壓力</label>
<input type="number" name="pressure" />
</div>
<div class="field">
<label>備註</label>
<textarea name="notes" rows="2"></textarea>
</div>
</fieldset>
<button type="submit">儲存</button>
</form>
<script type="module">
import { enableEnterAsTab } from './enter-as-tab.js';
enableEnterAsTab('#dataEntry');
</script>
| 需求 | 實現要點 |
|---|---|
| Shift+Enter 反向移動 | if (e.shiftKey) nextIndex = (currentIndex - 1 + len) % len |
| 最後欄位 Enter 提交 | if (currentIndex === len - 1) form.submit() |
| 跳過特定 class | 選擇器加 :not(.skip-enter-tab) |
| 支援 contenteditable | 選擇器加 [contenteditable="true"] |
| 行內編輯表格 | 綁定在 tbody,選擇器限定 td input |
textarea 預設保留換行功能 (Shift+Enter 或配置開關)data-enter-as-tab="false"{/* React Hook */}
function useEnterAsTab(formRef) {
useEffect(() => {
const form = formRef.current;
if (!form) return;
form.addEventListener('keydown', handleEnterAsTab);
return () => form.removeEventListener('keydown', handleEnterAsTab);
}, [formRef]);
}
{/* Vue 3 指令 */}
const vEnterTab = {
mounted(el) { el.addEventListener('keydown', handleEnterAsTab); },
unmounted(el) { el.removeEventListener('keydown', handleEnterAsTab); }
};
app.directive('enter-tab', vEnterTab);
// 使用:
「Enter 即 Tab」是提升資料錄入效率的關鍵細節。用通用、可配置、無障礙友善的方式實現,比硬編碼每個表單的 onkeydown 更可維護、更專業。