说明如何为自定义模态框实现焦点陷阱

解读

在国内企业级 Drupal 项目中,无障碍合规(等保 2.0、GB/T 37668-2019)与用户体验审计常被写进验收清单。模态框打开后,键盘用户若“跑”到背景元素,会被视为高危缺陷。焦点陷阱(Focus Trap)是前端面试高频考点,考官想确认两点:

  1. 你是否理解 Drupal 渲染管线与 Behaviors 生命周期;
  2. 你是否能用纯前端手段(不依赖庞大第三方库)写出符合 WCAG 2.1 2.4.3、2.1.2 的陷阱逻辑,并能在多语言、多主题、AJAX 换页场景下复用。

知识点

  • Drupal.behaviors 执行时机(AJAX 后重新 attach)
  • 可聚焦元素判定(tabindex >= 0、href、contentEditable、audio/video 带 controls 等)
  • 顺序焦点与编程焦点的区别(tab order vs. focus())
  • 键盘事件拦截(keydown@Tab、Shift+Tab)与 preventDefault 的边界条件
  • 无障碍语义(role="dialog"、aria-modal="true"、aria-hidden 背景)
  • 配置化与可测试性(Drupal.settings 注入、Jest/QUnit 用例)

答案

  1. 定义可复用 Behavior
(function (Drupal, once) {
  Drupal.behaviors.modalFocusTrap = {
    attach(context, settings) {
      const modalSelector = '[data-drupal-modal]';
      once('focus-trap', modalSelector, context).forEach(modal => {
        // 1. 收集陷阱内所有可聚焦元素
        const focusableString = [
          'a[href]', 'button:not([disabled])', 'input:not([type="hidden"]):not([disabled])',
          'select:not([disabled])', 'textarea:not([disabled])',
          '[tabindex]:not([tabindex="-1"])'
        ].join(',');
        const getFocusable = () => Array.from(modal.querySelectorAll(focusableString))
          .filter(el => el.offsetParent !== null);

        // 2. 记录触发元素,用于关闭后返回焦点
        const trigger = document.activeElement;
        let focusableList = getFocusable();
        const firstEl = focusableList[0];
        const lastEl = focusableList[focusableList.length - 1];

        // 3. 将焦点移入
        if (firstEl) firstEl.focus();

        // 4. 绑定键盘拦截
        const keyHandler = (e) => {
          if (e.key !== 'Tab') return;
          if (focusableList.length === 0) { e.preventDefault(); return; }

          if (e.shiftKey) { // Shift+Tab
            if (document.activeElement === firstEl) {
              e.preventDefault();
              lastEl.focus();
            }
          } else { // Tab
            if (document.activeElement === lastEl) {
              e.preventDefault();
              firstEl.focus();
            }
          }
        };
        modal.addEventListener('keydown', keyHandler);

        // 5. 监听 DOM 变化,动态更新陷阱范围
        const mo = new MutationObserver(() => {
          focusableList = getFocusable();
        });
        mo.observe(modal, { childList: true, subtree: true });

        // 6. 关闭时清理
        modal.addEventListener('drupal-modal-close', () => {
          modal.removeEventListener('keydown', keyHandler);
          mo.disconnect();
          if (trigger && typeof trigger.focus === 'function') trigger.focus();
        }, { once: true });
      });
    }
  };
})(Drupal, once);
  1. 模板层加语义属性
<div class="modal" data-drupal-modal role="dialog" aria-modal="true" aria-labelledby="modal-title">
  <h2 id="modal-title">{{ '选择地区'|t }}</h2>
  <button type="button" class="close" data-drupal-modal-close>{{ '关闭'|t }}</button>
  …
</div>
  1. 打开/关闭触发器
// 打开
const modal = document.querySelector('[data-drupal-modal]');
modal.classList.add('is-open');
modal.dispatchEvent(new Event('drupal-modal-open'));

// 关闭
modal.classList.remove('is-open');
modal.dispatchEvent(new Event('drupal-modal-close'));
  1. 自动化测试(QUnit 示例)
QUnit.test('焦点陷阱循环', assert => {
  const done = assert.async();
  const modal = document.querySelector('[data-drupal-modal]');
  const buttonInModal = modal.querySelector('button.save');
  buttonInModal.focus();

  const tabEvent = new KeyboardEvent('keydown', { key: 'Tab', shiftKey: false });
  modal.dispatchEvent(tabEvent);
  setTimeout(() => {
    assert.ok(document.activeElement === modal.querySelector('button.close'), 'Tab 到关闭按钮');
    done();
  }, 0);
});

拓展思考

  • 如果模态框内嵌 CKEditor 或 React 组件,焦点可能进入 iframe 或 Shadow DOM,此时需在收集函数里递归穿透 shadowRoot 并监听 blur 事件做兜底。
  • 国内政企项目常要求“信创”环境,需兼容统信 UOS 自带浏览器(基于 Chromium 70),MutationObserver 与 once 方法要做降级(polyfill)。
  • 对于 Headless 场景,Drupal 仅提供 JSON,前端用 Vue/React,陷阱逻辑可封装成可复用 Hook(useFocusTrap),但要在 Storybook 里提供 Drupal 主题变量注入示例,保证设计系统一致。
  • 性能压测时,若模态框含上千行表格,MutationObserver 会频繁触发,可改用防抖或只在打开瞬间静态计算,关闭后销毁。