Select(ComboBox)无障碍开发:键盘操作下aria标签能否切换元素控制?
ARIA与ComboBox键盘导航的状态更新
完全可行。ARIA属性正是为了让辅助技术感知动态组件状态而设计的,配合键盘操作更新这些属性,是无障碍ComboBox组件的核心要求。
对于下拉列表的上下箭头导航,你需要重点维护以下ARIA状态:
aria-selected:标记当前选中的选项(仅对当前激活的选项设为true,其他设为false)aria-activedescendant:在combobox元素上设置,指向当前通过键盘聚焦的选项ID,让屏幕阅读器识别哪个选项正在被导航aria-expanded:维护下拉列表的展开/收起状态(上下箭头操作一般在列表展开后进行,此状态通常保持true,除非用户按ESC收起)
下面是一个精简的示例,展示核心逻辑:
<div class="combobox-container"> <!-- 输入框:combobox角色,绑定下拉列表 --> <input type="text" role="combobox" id="demo-combobox" aria-expanded="true" aria-controls="demo-listbox" aria-activedescendant="option-1" > <!-- 下拉列表:listbox角色 --> <ul role="listbox" id="demo-listbox"> <li role="option" id="option-1" aria-selected="true">选项1</li> <li role="option" id="option-2" aria-selected="false">选项2</li> <li role="option" id="option-3" aria-selected="false">选项3</li> </ul> </div> <script> const combobox = document.getElementById('demo-combobox'); const options = Array.from(document.querySelectorAll('[role="option"]')); let currentIndex = 0; // 监听键盘事件 combobox.addEventListener('keydown', (e) => { switch(e.key) { case 'ArrowDown': e.preventDefault(); // 取消当前选项的选中状态 options[currentIndex].setAttribute('aria-selected', 'false'); // 更新索引,循环到开头 currentIndex = (currentIndex + 1) % options.length; // 设置新选项的选中状态 options[currentIndex].setAttribute('aria-selected', 'true'); // 更新combobox的activedescendant combobox.setAttribute('aria-activedescendant', options[currentIndex].id); break; case 'ArrowUp': e.preventDefault(); options[currentIndex].setAttribute('aria-selected', 'false'); // 更新索引,循环到结尾 currentIndex = (currentIndex - 1 + options.length) % options.length; options[currentIndex].setAttribute('aria-selected', 'true'); combobox.setAttribute('aria-activedescendant', options[currentIndex].id); break; } }); </script>
这个示例的核心逻辑:
- 初始状态下第一个选项被标记为选中,combobox指向该选项
- 按下上下箭头时,切换当前选项的
aria-selected状态 - 更新
aria-activedescendant让辅助技术感知当前聚焦的选项 - 用循环索引实现选项的循环导航
实际开发中还可以补充列表展开/收起、选项选中后的输入框值同步等逻辑,但以上代码已经覆盖了你关注的「键盘上下箭头更新ARIA状态」的核心需求,能帮你精简核心逻辑,保持代码整洁。
内容的提问来源于stack exchange,提问作者Taron Sarkisyan
相关产品推荐
相关产品推荐

