<label> 为表单控件提供一个无障碍名称和更大的点击区域。关联它们有两种方式,而这样做对无障碍性至关重要。
方式 1:for + id(显式)
html
<label for="email">Email address</label>
标签的 for 与输入框的 id 相匹配。即使它们在标记中不相邻,这种方式也有效。
<label>
Email address
<input type="email" />
</label>
输入框嵌套在标签内部——无需 id。
<label><input type="checkbox" /> I agree to the terms</label>
<!-- clicking the text toggles the checkbox -->
<input placeholder="Email" /> <!-- ❌ disappears on typing, poor contrast, not a label -->
placeholder 会在用户输入时消失,而且不能被可靠地朗读——绝不要把它当作唯一的标签。
<input type="search" aria-label="Search products" /> <!-- accessible name, no visible label -->
只有在确实无法提供可见标签时,才使用 aria-label(或 aria-labelledby)。
正确关联的标签是表单中最具影响力的无障碍实践之一——它们为每个控件赋予一个供辅助技术使用的名称,并为所有人扩大了点击区域。
优先使用真正的 <label>;只在必要时退而使用 aria-label,并且绝不要依赖 placeholder 充当标签。