萬盛學電腦網

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

JavaScript 判斷元素焦點狀態:document.activeElement 完整應用

核心 API

// 獲取當前聚焦元素
var activeEl = document.activeElement;

// 獲取 ID
var activeId = activeEl.id;
var activeIdJQ = $(document.activeElement).attr('id');

原生實作:精確比較元素引用

<input type="text" id="textID" />
<button onclick="checkFocus()">檢查</button>

function checkFocus() {
  var active = document.activeElement;
  var target = document.getElementById('textID');
  
  // 直接比較 DOM 節點引用(最可靠)
  if (active === target) {
    alert('true - 正在聚焦');
  } else {
    alert('false - 未聚焦,當前:' + (active.id || active.tagName));
  }
}

jQuery 封裝

// 方法一:is() 選擇器匹配
$('#textID').click(function() {
  var focused = $(document.activeElement).is('#textID');
  console.log(focused);
});

// 方法二:比較 ID
function isFocused(selector) {
  return $(document.activeElement).is(selector);
}

isFocused('#textID');  // true/false

// 方法三:取得焦點元素 ID
var focusedId = $(document.activeElement).attr('id');

進階應用場景

1. 表單驗證:聚焦第一個錯誤欄位

function focusFirstInvalid(formSelector) {
  var $form = $(formSelector);
  var $firstError = $form.find('[aria-invalid="true"], .error, :invalid').first();
  
  if ($firstError.length) {
    $firstError[0].focus();  // 原生 focus()
    $firstError[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
    return true;
  }
  return false;
}

2. 鍵盤快捷鍵:輸入框聚焦時禁用全域熱鍵

$(document).on('keydown', function(e) {
  // 如果焦點在輸入元素,不觸發全域快捷鍵
  var tag = document.activeElement.tagName.toLowerCase();
  var type = document.activeElement.type;
  var isInput = tag === 'input' || tag === 'textarea' || tag === 'select' || 
                document.activeElement.isContentEditable;
  
  if (isInput && (e.ctrlKey || e.metaKey)) {
    return;  // 讓瀏覽器處理複製/貼上等
  }
  
  // 全域快捷鍵邏輯
  if (e.key === 's' && e.ctrlKey) {
    e.preventDefault();
    saveData();
  }
});

3. 模態框焦點管理(無障礙 a11y)

function trapFocus($modal) {
  var focusable = $modal.find('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
  var first = focusable.first();
  var last = focusable.last();
  
  $modal.on('keydown', function(e) {
    if (e.key !== 'Tab') return;
    
    if (e.shiftKey) {
      if (document.activeElement === first[0]) {
        e.preventDefault();
        last.focus();
      }
    } else {
      if (document.activeElement === last[0]) {
        e.preventDefault();
        first.focus();
      }
    }
  });
  
  first.focus();  // 打開時聚焦第一個
}

常見誤區

  • 用 $(this).is(':focus') 在 click handler 中:click 觸發時焦點已在按鈕,永遠 false
  • 混淆 focus 事件與 document.activeElement:前者是事件,後者是狀態快照
  • iframe 跨域:無法訪問 iframe 內的 activeElement,需 postMessage 通訊

總結

  • document.activeElement 是判斷焦點的唯一標準屬性
  • 原生比較 === 最可靠,jQuery 用 .is(selector)
  • 善用 focusin/focusout 冒泡事件做表單級焦點追蹤
  • 無障礙開發需實作焦點陷阱
copyright © 萬盛學電腦網 all rights reserved