如何为模态框实现焦点陷阱(focus trap)?

解读

在国内前端/WordPress 面试中,焦点陷阱是衡量候选人是否具备“无障碍与交互一致性”意识的高频考点。
面试官想确认:

  1. 你是否理解焦点在模态框打开与关闭时的流向;
  2. 能否不依赖第三方库用原生 JS 或 WordPress 官方 API 完成闭环;
  3. 是否知道ESC 关闭、aria-hidden、滚动锁定等配套细节;
  4. 在 WordPress 场景下,能否与Gutenberg 区块、自定义器、媒体模态框共存而不冲突。

知识点

  • 可聚焦元素:a、button、input、select、textarea、[tabindex]≥0
  • tabindex 值策略:
    – 0 表示按 DOM 顺序参与 Tab 流;
    – -1 表示仅脚本聚焦,不进入 Tab 流;
    – ≥1 强制提前,国内可访问性测评会扣分,应避免。
  • 键盘事件:keydown(Tab、Shift+Tab、Escape)
  • DOM 端点:firstFocusableEl、lastFocusableEl
  • WordPress 自带:wp.element、wp.dom、wp.keycodes、wp.a11y.speak
  • Hook 点:
    – 前端:wp_enqueue_scripts 注入脚本;
    – 区块:useEffect 清理函数移除监听;
    – 自定义器:wp.customize.sectionConstructor 扩展。
  • 性能与安全:节流监听、销毁时 removeEventListener,防止内存泄漏导致后台卡顿。

答案

以下示例基于WordPress 5.9+、原生 ES6、无第三方依赖,可直接放入主题或插件的 js/src/modal-focus-trap.js,并通过 wp_enqueue_scripts 引入。

/**
 * WordPress 模态框焦点陷阱
 * 1. 打开时保存前一焦点
 * 2. 限制 Tab 只在框内循环
 * 3. ESC 关闭并归还焦点
 */
( function( wp ) {
    const MODAL_CLASS   = 'my-modal';          // 模态框根节点类
    const ACTIVE_CLASS  = 'is-open';           // 打开状态类
    const FOCUSABLE_SEL = 'a[href],button,input,select,textarea,[tabindex]:not([tabindex="-1"])';

    let previousFocus   = null;
    let modalNode       = null;
    let firstEl         = null;
    let lastEl          = null;

    function getFocusableEls() {
        return Array.from( modalNode.querySelectorAll( FOCUSABLE_SEL ) )
                    .filter( el => el.offsetParent !== null ); // 过滤隐藏元素
    }

    function trap( e ) {
        if ( e.key !== 'Tab' ) return;
        if ( e.key === 'Escape' ) {
            closeModal();
            return;
        }
        if ( e.shiftKey && document.activeElement === firstEl ) {
            e.preventDefault();
            lastEl.focus();
        } else if ( !e.shiftKey && document.activeElement === lastEl ) {
            e.preventDefault();
            firstEl.focus();
        }
    }

    function openModal( selector ) {
        modalNode = 'string' === typeof selector
                    ? document.querySelector( selector )
                    : selector;
        if ( ! modalNode ) return;
        previousFocus = document.activeElement;
        modalNode.classList.add( ACTIVE_CLASS );
        modalNode.setAttribute( 'aria-hidden', 'false' );

        const focusableEls = getFocusableEls();
        if ( focusableEls.length ) {
            firstEl = focusableEls[0];
            lastEl  = focusableEls[ focusableEls.length - 1 ];
            firstEl.focus();
        } else {
            modalNode.focus(); // 兜底:模态框自身需 tabindex="-1"
        }
        document.addEventListener( 'keydown', trap, true ); // useCapture 提前拦截
    }

    function closeModal() {
        if ( ! modalNode ) return;
        modalNode.classList.remove( ACTIVE_CLASS );
        modalNode.setAttribute( 'aria-hidden', 'true' );
        document.removeEventListener( 'keydown', trap, true );
        if ( previousFocus && previousFocus.focus ) {
            previousFocus.focus();
        }
        modalNode = null;
    }

    // 暴露给全局,方便 PHP 或区块调用
    wp.myModal = { open: openModal, close: closeModal };
} )( window.wp );

PHP 侧调用示例(主题 functions.php):

add_action( 'wp_enqueue_scripts', function () {
    wp_register_script(
        'my-modal-focus',
        get_theme_file_uri( 'js/src/modal-focus-trap.js' ),
        [ 'wp-dom', 'wp-keycodes' ], // 依赖官方包,保证版本一致
        wp_get_theme()->get( 'Version' ),
        true
    );
    wp_enqueue_script( 'my-modal-focus' );
});

关键点回顾

  1. 使用 useCapture=true 捕获阶段拦截,避免被内部阻止冒泡的脚本打乱;
  2. 关闭时归还焦点,保证无障碍链路完整;
  3. 监听销毁必须 removeEventListener,防止在 WordPress 单页自定义器反复打开时重复绑定;
  4. 若与 Gutenberg 内嵌模态框共存,需在打开前判断 document.body.classList.contains( 'block-editor-page' ) 并复用 wp.data.dispatch( 'core/block-editor' ).__experimentalSetIsInserterOpened( false ) 关闭侧边栏,避免双焦点陷阱冲突。

拓展思考

  • 国内监管要求:2025 年《互联网无障碍专项行动》将强制政府/教育/医疗站点达到 WCAG 2.1 3.2.1(焦点顺序),焦点陷阱实现不合格会被通报。
  • 性能优化:对包含富文本或大量表单的模态框,可在打开时动态计算 focusable 数组并缓存,减少 DOM 查询;关闭时清空缓存,防止文章列表页打开多个模态框时内存堆积。
  • 与 Elementor、小工具弹窗共存:国内很多站点使用 Elementor Pro 弹窗,其已内置 e-a11y-focus-trap 类,可通过 elementorFrontend.on( 'components:init' ) 监听,主动禁用自身陷阱,避免双陷阱导致 Tab 失效。
  • E2E 测试:使用 @wordpress/e2e-test-utils 的 pressKeyWithModifier( 'Tab' ) 编写用例,断言 await page.evaluate( () => document.activeElement.classList.contains( 'expected-el' ) ),确保 CI 流水线自动回归。