概述通过语义化标签与ARIA属性, 将输入错误与校验结果以可达方式呈现, 读屏能正确报读并且键盘用户可流畅导航, 提升表单可用性与一致性。关键实践与参数关联标签: `label for` 与 `aria-labelledby`状态指示: `aria-invalid` `aria-describedby` 指向错误描述实时反馈: 使用 `aria-live="polite"` 或 `assertive`聚焦管理: 错误时聚焦到第一个错误字段或提示区域示例/配置/实现<form id="f"> <div> <label for="email">邮箱</label> <input id="email" name="email" type="email" aria-describedby="email-err"> <div id="email-err" role="alert" aria-live="polite"></div> </div> <div> <label for="pwd">密码</label> <input id="pwd" name="pwd" type="password" minlength="8" aria-describedby="pwd-err"> <div id="pwd-err" role="alert" aria-live="polite"></div> </div> <button type="submit">提交</button> <div id="form-msg" aria-live="assertive"></div> }</form> const f = document.getElementById('f') f.addEventListener('submit', (e) => { e.preventDefault() let firstErr = null const email = document.getElementById('email') const pwd = document.getElementById('pwd') const emailErr = document.getElementById('email-err') const pwdErr = document.getElementById('pwd-err') emailErr.textContent = '' pwdErr.textContent = '' email.removeAttribute('aria-invalid') pwd.removeAttribute('aria-invalid') if (!email.value || !email.value.includes('@')) { email.setAttribute('aria-invalid', 'true'); emailErr.textContent = '请输入有效邮箱'; firstErr = firstErr || email } if (!pwd.value || pwd.value.length < 8) { pwd.setAttribute('aria-invalid', 'true'); pwdErr.textContent = '密码至少8位'; firstErr = firstErr || pwd } if (firstErr) firstErr.focus() else document.getElementById('form-msg').textContent = '提交成功' }) 验证读屏反馈: 错误提示被读屏报读, 成功消息在Live Region播报键盘导航: 仅用键盘完成输入与提交, 错误聚焦到首个问题字段视觉提示: 错误状态明显且与文本提示一致指标: 使用Lighthouse/axe提升可访问性评分注意事项避免仅用颜色传达状态, 提供文本与语义国际化与本地化文本适配读屏在复杂表单中保持焦点顺序与逻辑一致与框架表单库集成时保持ARIA属性正确传递

发表评论 取消回复