萬盛學電腦網

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

JavaScript Enter 鍵實現 Tab 鍵切換焦點:表單密集輸入場景解決方案

在資料錄入密集型系統 (ERP、POS、倉管、實驗室記錄) 中,使用者習慣用數字鍵盤的 Enter 鍵在欄位間移動,而非 Tab。本文實現一個通用的「Enter 即 Tab」指令,支援動態表單、巢狀結構、跳過不可見/禁用元素,並解決事件冒泡、預設行為阻止等細節問題。

核心需求分析

  • 觸發鍵:Enter (keyCode 13 / key 'Enter')
  • 目標元素:可聚焦的表單控件 (input、select、textarea、button)
  • 順序:DOM 文檔順序 (視覺順序通常一致)
  • 邊界:最後一個元素可選提交表單或循環回第一個
  • 排除:type="hidden"、disabled、readonly、display:none、type="button/submit/reset" (視需求)

現代實作:ES6 模組化指令

// 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);

jQuery 版本 (維護舊專案用)

// 原文邏輯改良版:支援動態元素、正確選擇器
$(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();
    }
  }
});

HTML 結構範例

<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

無障礙 (a11y) 考量

  • 保留 Tab 原生導航,Enter 為增強而非替代
  • textarea 預設保留換行功能 (Shift+Enter 或配置開關)
  • 提供關閉開關:data-enter-as-tab="false"
  • 螢幕閱讀器用戶依賴標準 Tab 順序,勿破壞

React / Vue 整合範例

{/* 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 更可維護、更專業。

copyright © 萬盛學電腦網 all rights reserved