复杂表单无障碍与可用性增强:ARIA反馈、焦点顺序与错误提示实践技术背景复杂表单常见问题包括:焦点顺序不合理、错误提示不可达、屏幕阅读器信息不完整、键盘操作不友好。遵循语义化与 ARIA 规范,结合清晰的错误提示与校验策略,可显著提升表单的易用性与可访问性。核心内容语义化结构与关联<form aria-labelledby="profile-title">
<h1 id="profile-title">个人信息</h1>
<div>
<label for="name">姓名</label>
<input id="name" name="name" required aria-required="true" />
</div>
<div>
<label for="email">邮箱</label>
<input id="email" name="email" type="email" required aria-required="true" aria-describedby="email-help" />
<small id="email-help">将用于通知与登录</small>
</div>
<button type="submit">提交</button>
<div role="status" aria-live="polite" class="sr-only" id="form-status"></div>
<div role="alert" id="form-error" class="sr-only"></div>
<a href="#main" class="skip-link">跳到主要内容</a>
<main id="main"></main>
</form>
错误提示与焦点定位function setFieldError(input: HTMLElement, message: string) {
const id = input.getAttribute('id') || '';
let err = document.getElementById(`${id}-error`);
if (!err) {
err = document.createElement('div');
err.id = `${id}-error`;
err.setAttribute('role', 'alert');
err.className = 'field-error';
input.insertAdjacentElement('afterend', err);
input.setAttribute('aria-invalid', 'true');
input.setAttribute('aria-describedby', `${id}-error`);
}
err.textContent = message;
(input as HTMLElement).focus();
}
function clearFieldError(input: HTMLElement) {
input.removeAttribute('aria-invalid');
const id = input.getAttribute('id') || '';
const err = document.getElementById(`${id}-error`);
if (err) err.remove();
}
键盘可达性与焦点顺序function enforceFocusOrder(container: HTMLElement) {
const focusables = container.querySelectorAll<HTMLElement>('a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
const first = focusables[0];
const last = focusables[focusables.length - 1];
container.addEventListener('keydown', (e) => {
if (e.key !== 'Tab') return;
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
});
}
技术验证参数在 Chrome 128/Edge 130/Safari 17(多终端)下:键盘可达性覆盖:主流程 100%屏幕阅读器提示完整度:≥ 98%错误提示可达性:≥ 99%表单完成率(可用性测试):提升 10–25%应用场景多步骤表单与复杂业务流程验证与提示密集的后台系统合规与公共服务场景最佳实践语义化结构优先,ARIA 用于补充明确错误提示与焦点定位策略提供跳转链接与焦点陷阱,保证可达性

发表评论 取消回复