You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为菜单展开/收起图标设置键盘焦点的最佳实现方案

为菜单切换图标添加键盘焦点的最佳实践

优先方案:使用<button>元素(推荐)

这是无障碍友好的最优解,<button>原生具备适配需求的核心特性:

  • 默认支持键盘焦点,可通过Tab键选中
  • 自带键盘交互逻辑:按下Enter或空格即可触发点击事件
  • 语义明确,屏幕阅读器会自动识别为可交互按钮,无需额外配置

代码示例

<button type="button" class="menu-toggle" aria-expanded="false" aria-label="切换菜单状态">
  <i class="chevron-icon"></i> <!-- 此处放置你的Chevron图标 -->
</button>

关键属性说明

  • type="button":避免按钮在表单环境下默认触发提交行为
  • aria-expanded:动态切换true/false,告知屏幕阅读器当前菜单的展开/收起状态
  • aria-label:为无文本的图标按钮提供描述,确保屏幕阅读器用户能理解按钮功能

配套JS逻辑

const toggleBtn = document.querySelector('.menu-toggle');
const menu = document.querySelector('.your-menu-selector');

toggleBtn.addEventListener('click', function() {
  const isExpanded = this.getAttribute('aria-expanded') === 'true';
  // 切换Chevron图标方向
  this.querySelector('.chevron-icon').classList.toggle('chevron-up', !isExpanded);
  this.querySelector('.chevron-icon').classList.toggle('chevron-down', isExpanded);
  // 切换菜单显示/隐藏
  menu.classList.toggle('hidden', isExpanded);
  // 更新无障碍状态属性
  this.setAttribute('aria-expanded', !isExpanded);
});

备选方案:使用<a>标签(不推荐)

如果受现有代码限制必须使用<a>标签,可通过阻止默认跳转行为解决页面刷新问题,同时保留自定义点击逻辑:

代码示例

<a href="#" class="menu-toggle" aria-expanded="false" aria-label="切换菜单状态">
  <i class="chevron-icon"></i>
</a>

配套JS逻辑

document.querySelector('.menu-toggle').addEventListener('click', function(e) {
  e.preventDefault(); // 仅阻止默认页面跳转,不影响自定义点击逻辑
  // 菜单切换与图标更新逻辑同上述<button>方案
  const isExpanded = this.getAttribute('aria-expanded') === 'true';
  this.setAttribute('aria-expanded', !isExpanded);
  // ...其他操作
});

注意:<a>标签的语义是导航链接,用于触发菜单切换属于语义误用,仅作为兼容旧代码的临时方案。


内容的提问来源于stack exchange,提问作者kevinzf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 08:45:29