状态 控件状态
aria-selected
表示单选或多选容器中的某个条目当前处于已选中状态。适用于 tab、option、gridcell、treeitem 等角色。与 aria-checked(复选框/单选按钮)和 aria-pressed(切换按钮)含义不同。
何时使用
用于属于具有选择模型的容器内的条目:
tablist中的role="tab"(恰好选中一个)。listbox中的role="option"(根据aria-multiselectable可选一个或多个)。tree中的role="treeitem"。grid中的role="gridcell"、role="row"、role="columnheader"、role="rowheader"。
该状态描述的是条目与其容器选择模型之间的关系,而非像复选框那样独立的开/关状态。请根据使用场景选择正确的状态:
aria-selected— 用于 tab、option、tree 或 grid 上下文中的条目。aria-checked— 用于复选框和单选按钮(独立选择)。aria-pressed— 用于切换按钮(按钮本身处于开或关状态)。
一个常见错误是在 <button> 上设置 aria-selected="true" 来表示「用户上次点击了它」。如果元素不属于选择类组件,应使用 aria-pressed 或 aria-current。
如何保持同步
有效值为 "true" 和 "false"。请在未选中的条目上渲染 "false" 而非省略该属性 — 这样辅助技术才能正确宣告「第 1 项,共 5 项」等位置信息。在单选组件(tablist、单选 listbox)中,任意时刻应恰好有一个条目为 "true"。
该属性必须与视觉指示器和焦点管理保持同步更新。在 tablist 中,切换选中状态通常还需将 tabindex="0" 移至当前选中的 tab,并将其他 tab 设置为 tabindex="-1"。
常见错误
- 在任何选择类容器之外的按钮或链接上使用
aria-selected。 - 在单选 tablist 或 listbox 中存在多个
aria-selected="true"条目。 - 选中状态移动后,忘记将原先选中条目的
aria-selected重置为"false"。 - 通过 CSS 呈现「已选中」外观,却未同步更新属性值。
- 将
aria-selected与aria-checked混淆用于 listbox 选项(始终使用selected),或与aria-current混淆用于导航链接(应使用current,而非selected)。 - 在
role="menuitem"上设置aria-selected— 菜单条目不支持此属性;对菜单复选框/单选按钮应使用aria-checked。
示例
<div role="tablist" aria-label="Sections">
<button role="tab" id="tab-1" aria-selected="true" tabindex="0" aria-controls="panel-1">Overview</button>
<button role="tab" id="tab-2" aria-selected="false" tabindex="-1" aria-controls="panel-2">Details</button>
<button role="tab" id="tab-3" aria-selected="false" tabindex="-1" aria-controls="panel-3">Reviews</button>
</div>