表單錄入密集頁面,用戶期望按 Enter 鍵像 Tab 一樣跳轉到下一個可輸入控件,提升錄入效率。
/**
* Enter 鍵聚焦下一個表單元素
* @param {HTMLFormElement|HTMLDocument} scope - 搜索範圍,默認 document
*/
function enableEnterFocus(scope) {
scope = scope || document;
// 收集所有可聚焦表單元素:input/select/textarea/button (排除 hidden/disabled/readonly)
var focusable = Array.prototype.slice.call(scope.querySelectorAll(
'input:not([type=hidden]):not([disabled]):not([readonly]), ' +
'select:not([disabled]), ' +
'textarea:not([disabled]):not([readonly]), ' +
'button:not([disabled])'
));
focusable.forEach(function(el, index) {
el.addEventListener('keydown', function(e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// 阻止默認提交行為 (在 form 中)
if (e.target.tagName !== 'TEXTAREA') {
e.preventDefault();
}
// 找下一個可聚焦元素
var next = focusable[index + 1];
if (next) {
next.focus();
// 如果是 input/select,可選中內容
if (next.select) next.select();
} else {
// 最後一個:可選提交表單或循環到第一個
// focusable[0].focus();
}
}
});
});
}
// 頁面加載後啟用
document.addEventListener('DOMContentLoaded', function() {
enableEnterFocus(document.forms[0]); // 或 document
});
$(function() {
var $inputs = $('input:visible:not([readonly]), select:visible, textarea:visible')
.filter(function() { return !this.disabled; });
$inputs.on('keydown', function(e) {
if (e.keyCode === 13) { // Enter
var idx = $inputs.index(this);
if (idx >= 0 && idx < $inputs.length - 1) {
e.preventDefault(); // 阻止 form 提交
$inputs.eq(idx + 1).focus().select();
}
}
});
});
$inputs.on('keydown', function(e) {
if (e.keyCode !== 13) return; // 非 Enter
var idx = $inputs.index(this);
if (idx === -1) return;
if (e.shiftKey) { // Shift+Enter → 上一個
if (idx > 0) {
e.preventDefault();
$inputs.eq(idx - 1).focus().select();
}
} else { // Enter → 下一個
if (idx < $inputs.length - 1) {
e.preventDefault();
$inputs.eq(idx + 1).focus().select();
} else {
// 最後一個:提交表單或自定義
// $(this).closest('form').submit();
}
}
});
| 情況 | 處理策略 |
|---|---|
<textarea> | 允許換行,不攔截 Enter,僅 Ctrl+Enter 跳轉 |
按鈕 <button> | Enter 觸發 click,不跳轉焦點 |
下拉選單 <select> | 展開時 Enter 確認選擇,關閉時跳轉 |
| 動態添加元素 | 使用事件委託 $(form).on('keydown', 'selector', fn) |
| 嵌套表單/Shadow DOM | 傳入具體 scope 範圍 |
<!-- 指定 Tab 順序,Enter 行為由瀏覽器決定 -->
<input tabindex="1">
<input tabindex="2">
<select tabindex="3"></select>
<!-- HTML5 表單驗證配合 -->
<input required>
<input type="email" required>
<button type="submit">提交</button>
現代瀏覽器在表單中 Enter 默認提交,配合 tabindex 控制順序,大多數場景無需 JS 干預。
aria-live)