萬盛學電腦網

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

JavaScript/jQuery 獲取輸入框焦點與表單驗證實戰模式

表單驗證失敗時自動聚焦首個錯誤字段,是提升用戶體驗的關鍵細節。本文對比原生 JS 與 jQuery 兩種實現模式,並提供可復用的驗證聚焦工具函數。

模式一:原生 JS 表單驗證 + 聚焦

function checkForm() {
  var form = document.form1; // 通過 name 獲取表單
  var trainingName = form.trainingName; // 通過 name 獲取字段
  
  if (trainingName.value === '') {
    alert('培訓班名稱不能為空!');
    trainingName.focus(); // 原生 focus() 方法
    return false; // 阻止提交
  }
  return true;
}

// HTML
<form name="form1" onsubmit="return checkForm()">
  <input name="trainingName" type="text">
  <button type="submit">提交</button>
</form>

模式二:jQuery 事件綁定 + 正則驗證 + 聚焦

function checkForm() {
  var $classLevel = $('#classLevel');
  var val = $classLevel.val().trim();
  var re = /^[1-9]\d*$/; // 正整數正則
  
  if (!re.test(val) && val.length > 0) {
    alert('請輸入大於零的整數!');
    $classLevel.focus(); // jQuery focus() 觸發原生 focus 事件
    return false;
  }
  return true;
}

// 綁定提交事件 (推薦非內聯方式)
$('#myForm').on('submit', function(e) {
  if (!checkForm()) e.preventDefault();
});

通用表單驗證聚焦工具函數

var FormValidator = {
  rules: {
    required: function(val) { return val.trim() !== ''; },
    integer: function(val) { return /^[1-9]\d*$/.test(val); },
    mobile: function(val) { return /^1[3-9]\d{9}$/.test(val); },
    email: function(val) { return /^[\w.-]+@[\w-]+\.[\w.-]+$/.test(val); }
  },
  
  messages: {
    required: '此字段為必填',
    integer: '請輸入正整數',
    mobile: '手機號格式不正確',
    email: '郵箱格式不正確'
  },
  
  validate: function(formSelector) {
    var $form = $(formSelector);
    var firstInvalid = null;
    
    $form.find('[data-rule]').each(function() {
      var $field = $(this);
      var rules = $field.data('rule').split(' ');
      var val = $field.val();
      
      for (var i = 0; i < rules.length; i++) {
        var rule = rules[i];
        if (FormValidator.rules[rule] && !FormValidator.rules[rule](val)) {
          alert(FormValidator.messages[rule]);
          if (!firstInvalid) firstInvalid = $field;
          return false; // 跳出當前字段規則循環
        }
      }
    });
    
    if (firstInvalid) {
      firstInvalid.focus(); // 聚焦首個錯誤字段
      return false;
    }
    return true;
  }
};

// HTML 使用
/*
*/

焦點管理進階技巧

1. 頁面加載自動聚焦首個輸入框

// 原生
window.onload = function() {
  document.querySelector('input:not([type=hidden]), textarea, select').focus();
};

// jQuery
$(function() {
  $('input:visible, textarea:visible, select:visible').first().focus();
});

2. 鍵盤 Enter 鍵提交表單並聚焦下一字段

$(document).on('keydown', 'input:not([type=submit]), textarea', function(e) {
  if (e.keyCode === 13) { // Enter
    e.preventDefault();
    var $fields = $(this).closest('form').find('input:visible, textarea:visible, select:visible, button:visible');
    var idx = $fields.index(this);
    if (idx >= 0 && idx < $fields.length - 1) {
      $fields.eq(idx + 1).focus();
    } else {
      $(this).closest('form').submit();
    }
  }
});

3. 模態框打開時聚焦、關閉時恢復焦點

var lastFocused = null;

function openModal($modal) {
  lastFocused = document.activeElement; // 記錄打開前焦點
  $modal.show();
  $modal.find('input, textarea, select, button').filter(':visible').first().focus();
}

function closeModal($modal) {
  $modal.hide();
  if (lastFocused) lastFocused.focus(); // 恢復焦點
}

無障礙 (a11y) 焦點最佳實踐

  • 可聚焦元素必須有明顯 :focus 樣式 (勿只用 outline: none)
  • 動態插入內容後,將焦點移至新內容首個可交互元素
  • 避免焦點陷阱:Tab 循環在模態框內,Shift+Tab 反向循環
  • 使用 autofocus 屬性聲明式指定初始焦點 (HTML5)

良好的焦點管理是表單體驗的隱形質量線,投入少量代碼,收穫顯著的用戶滿意度提升。

copyright © 萬盛學電腦網 all rights reserved