Tailwind CSS Academy · 课时

无障碍模态框与下拉菜单

添加 aria-modal、role dialog、焦点锁定和键盘 Escape 处理,确保覆盖层组件完全符合无障碍要求。

第 4 / 4 课13 个步骤

无障碍模态框与下拉菜单 是 CoddyKit 上的免费 Tailwind CSS Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Tailwind CSS Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Tailwind CSS Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Accessibility Is Non-Negotiable

Modals and dropdowns are among the most commonly used interactive patterns in web UIs, and they are also among the most frequently inaccessible. Users who rely on screen readers, keyboard-only navigation, or switch controls cannot use poorly implemented overlays.

Making these components accessible is not optional — it is required by WCAG 2.1 (Web Content Accessibility Guidelines) and by laws like the ADA and the EU Web Accessibility Directive. Beyond compliance, accessible components are simply better UX for everyone.

Focus Management When Modal Opens

When a modal opens, keyboard focus must move into the modal so keyboard users do not have to tab all the way through the page to reach the modal's controls. Programmatically focus the first interactive element — usually the close button or the first form field.

Store a reference to the element that triggered the modal (const trigger = document.activeElement) before opening, so you can return focus to it when the modal closes. This preserves the user's navigation position in the page.

<script>
  let triggerEl = null;

  function openModal() {
    triggerEl = document.activeElement; // save current focus position
    const modal = document.getElementById('modal');
    modal.classList.remove('hidden');
    document.body.classList.add('overflow-hidden');

    // Move focus into the modal
    const firstFocusable = modal.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    if (firstFocusable) firstFocusable.focus();
  }

  function closeModal() {
    document.getElementById('modal').classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
    // Return focus to trigger
    if (triggerEl) triggerEl.focus();
  }
</script>

Focus Trapping Inside the Modal

While the modal is open, Tab and Shift+Tab must cycle only through the modal's interactive elements and not escape to the page behind it. This is called a focus trap.

Implement it by finding all focusable elements within the modal, detecting when the last one is focused and Tab is pressed (wrapping to the first), and detecting when the first is focused and Shift+Tab is pressed (wrapping to the last).

<script>
  function trapFocus(modalEl) {
    const focusable = modalEl.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    const firstEl = focusable[0];
    const lastEl = focusable[focusable.length - 1];

    modalEl.addEventListener('keydown', (e) => {
      if (e.key !== 'Tab') return;
      if (e.shiftKey) {
        // Shift+Tab on first element -> wrap to last
        if (document.activeElement === firstEl) {
          e.preventDefault();
          lastEl.focus();
        }
      } else {
        // Tab on last element -> wrap to first
        if (document.activeElement === lastEl) {
          e.preventDefault();
          firstEl.focus();
        }
      }
    });
  }
</script>

ARIA for Modal Dialogs

Modals require specific ARIA attributes for screen readers to understand the dialog context:

  • role='dialog' — identifies the element as a dialog
  • aria-modal='true' — tells assistive technology that content behind the dialog is inert
  • aria-labelledby — points to the dialog's visible title element
  • aria-describedby — optionally points to a description paragraph

Without these, a screen reader user opening a modal may not know they are in a dialog at all.

<div
  id="modal"
  role="dialog"
  aria-modal="true"
  aria-labelledby="modal-heading"
  aria-describedby="modal-desc"
  class="fixed inset-0 flex items-center justify-center z-50 p-4 hidden">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
    <h2 id="modal-heading" class="text-lg font-semibold text-gray-900">Confirm Action</h2>
    <p id="modal-desc" class="mt-2 text-sm text-gray-600">
      This action will permanently delete your account.
    </p>
    <div class="mt-5 flex justify-end gap-3">
      <button onclick="closeModal()" class="px-4 py-2 text-sm font-semibold border border-gray-300 rounded-lg">Cancel</button>
      <button class="px-4 py-2 text-sm font-semibold text-white bg-red-600 rounded-lg">Delete</button>
    </div>
  </div>
</div>

Making Background Content Inert

When a modal is open, all page content behind the backdrop should be made inert — not focusable and not interactable by screen readers. The HTML inert attribute achieves this natively, and it is now supported in all modern browsers.

Apply inert to the main content area (not the modal or backdrop) when the modal opens, and remove it when the modal closes. This provides a native alternative to complex aria-hidden attribute management.

<script>
  const mainContent = document.getElementById('main-content');

  function openModal() {
    // Make everything behind the modal inert
    mainContent.setAttribute('inert', '');
    mainContent.setAttribute('aria-hidden', 'true');

    document.getElementById('modal').classList.remove('hidden');
    document.body.classList.add('overflow-hidden');
  }

  function closeModal() {
    // Restore background content
    mainContent.removeAttribute('inert');
    mainContent.removeAttribute('aria-hidden');

    document.getElementById('modal').classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
  }
</script>

Dropdown ARIA Roles

Accessible dropdown menus require ARIA attributes on both the trigger and the panel. The trigger button gets aria-haspopup='true' (or aria-haspopup='menu') and aria-expanded='false'. When opened, update aria-expanded to 'true'.

The dropdown panel gets role='menu', and each item inside it gets role='menuitem'. This full role set allows screen readers to announce the dropdown as a menu and navigate items with arrow keys.

<div class="relative inline-block">
  <!-- Trigger with ARIA -->
  <button
    id="dd-btn"
    aria-haspopup="menu"
    aria-expanded="false"
    aria-controls="dd-menu"
    onclick="toggleDropdown()"
    class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium
           text-gray-700 bg-white border border-gray-300 rounded-lg
           hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
    Account
    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
    </svg>
  </button>
  <!-- Panel with role=menu -->
  <div
    id="dd-menu"
    role="menu"
    aria-labelledby="dd-btn"
    class="hidden absolute top-full left-0 mt-1 z-50 w-56 bg-white border border-gray-200 rounded-xl shadow-lg py-1">
    <a href="/profile" role="menuitem" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Profile</a>
    <a href="/settings" role="menuitem" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Settings</a>
  </div>
</div>

Arrow Key Navigation in Dropdowns

WCAG requires that dropdown menu items be navigable with arrow keys: Down Arrow moves to the next item, Up Arrow moves to the previous, Home moves to the first, End moves to the last. This mirrors native OS menu behavior that keyboard users expect.

Implement this by adding a keydown listener on the menu panel that moves focus between role='menuitem' elements. Items should receive tabindex='-1' so they are programmatically focusable but not part of the Tab order.

<script>
  document.getElementById('dd-menu').addEventListener('keydown', (e) => {
    const items = [...document.querySelectorAll('[role=menuitem]')];
    const idx = items.indexOf(document.activeElement);

    if (e.key === 'ArrowDown') {
      e.preventDefault();
      items[(idx + 1) % items.length].focus();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      items[(idx - 1 + items.length) % items.length].focus();
    } else if (e.key === 'Home') {
      e.preventDefault();
      items[0].focus();
    } else if (e.key === 'End') {
      e.preventDefault();
      items[items.length - 1].focus();
    } else if (e.key === 'Escape') {
      closeDropdown();
      document.getElementById('dd-btn').focus();
    }
  });
</script>

Visible Focus Styles on All Interactive Elements

Every button, link, and interactive element inside a modal or dropdown must have a clearly visible focus indicator. Tailwind's focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-1 provides this for keyboard users without showing a ring on mouse clicks.

Remove any outline-none classes on interactive elements unless you are providing a custom focus style in its place. Invisible focus is a WCAG failure.

<!-- Close button in a modal -->
<button
  onclick="closeModal()"
  aria-label="Close dialog"
  class="p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg
         focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500
         focus-visible:ring-offset-1 transition-colors">
  <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
  </svg>
</button>

Screen Reader Only Text With sr-only

Sometimes a button's visible icon is self-explanatory visually, but a screen reader needs text to announce it. Tailwind's sr-only utility visually hides text while keeping it accessible to screen readers.

Use sr-only for icon-button labels when you do not want to use aria-label, or when you want the text to be part of the DOM (useful for some screen reader behaviors). The class applies position: absolute; width: 1px; height: 1px; overflow: hidden — making it invisible but present.

<!-- Icon button with sr-only label -->
<button
  class="p-2 text-gray-500 hover:bg-gray-100 rounded-lg
         focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500">
  <svg class="w-5 h-5" aria-hidden="true" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
  </svg>
  <span class="sr-only">Close modal</span>
</button>

Color Contrast in Overlays

Text inside modals and dropdown menus must meet WCAG AA contrast ratios: at least 4.5:1 for normal text and 3:1 for large text. Dark text on white backgrounds easily meets this, but subtle grays on white can fail.

The color text-gray-400 on a white background (#9ca3af on #fff) has a contrast ratio of approximately 2.5:1 — failing WCAG AA. Always use at least text-gray-500 (#6b7280, ~4.6:1) for body text in modals and text-gray-900 for primary text.

<!-- Failing contrast -->
<p class="text-gray-400">Helper text (fails WCAG AA)</p>

<!-- Passing contrast -->
<p class="text-gray-500">Helper text (passes WCAG AA ~4.6:1)</p>
<p class="text-gray-600">Body text (strong contrast ~5.9:1)</p>
<h2 class="text-gray-900">Heading (maximum contrast ~21:1)</h2>

Live Region Announcements

When dynamic content appears inside a modal or dropdown (like a loading spinner transitioning to results), a live region ensures screen readers announce the change without the user having to navigate to it. Add aria-live='polite' to a container element that will receive updates.

aria-live='polite' queues the announcement for when the user is idle. Use aria-live='assertive' only for critical errors that need immediate interruption. Overusing assertive announcements is disruptive.

<div class="p-6">
  <!-- Loading state -->
  <div id="modal-status" aria-live="polite" aria-atomic="true" class="text-center">
    <p class="text-sm text-gray-600">Loading results...</p>
  </div>
</div>

<script>
  // After data loads, update the region
  // Screen reader will announce the change
  function showResults(data) {
    document.getElementById('modal-status').innerHTML =
      '<p class="text-sm text-green-600">Found ' + data.length + ' results.</p>';
  }
</script>

Quick Check

Test your understanding of Tailwind CSS Mastery concepts from this lesson.

Lesson Recap

In this lesson you learned: modal accessibility requires focus management (trap focus inside, return focus on close), role='dialog' aria-modal='true', and the HTML inert attribute to lock background content; dropdown ARIA uses role='menu' on the panel, role='menuitem' on items, aria-haspopup='menu' and aria-expanded on the trigger; and Tailwind's sr-only provides screen-reader-only labels for icon-only controls. Next up we explore how the JIT engine works.

免费开始

用 AI 导师学习 HTML — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「无障碍模态框与下拉菜单」课时是免费的吗?

是的 — 「无障碍模态框与下拉菜单」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Tailwind CSS Academy 课程的其余内容,请升级到 CoddyKit PRO。 Tailwind CSS Academy 课程共包含 4 节课。

「无障碍模态框与下拉菜单」这节课中我会学到什么?

添加 aria-modal、role dialog、焦点锁定和键盘 Escape 处理,确保覆盖层组件完全符合无障碍要求。 你通过在浏览器中直接运行的动手代码来练习 Tailwind CSS Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Tailwind CSS Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Tailwind CSS Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「无障碍模态框与下拉菜单」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Tailwind CSS Academy 课中编写并运行代码吗?

能。每节 Tailwind CSS Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 模态对话框结构
  2. 模态框打开与关闭动画
  3. 下拉菜单组件
  4. 无障碍模态框与下拉菜单
← 返回 Tailwind CSS Academy