点击Accordion时阻止页面滚动,该方案的可访问性是否达标?
手风琴组件(Accordion)的可访问性方案选择
问题背景
我基于一款宣称具备良好可访问性的手风琴代码构建组件,为实现展开/收起的过渡动画做了小幅修改后,出现点击按钮随内容展开被推离视野的问题。
问题原因如下:
页面会保持当前激活元素(即点击的按钮)在视野内,因此额外高度会根据按钮在屏幕上的位置向上或向下移动页面。
我目前采用了阻止页面滚动的方案,认为更符合可访问性要求,但另有方案建议模糊元素。我疑惑模糊元素是否会影响屏幕阅读器与按钮的交互,想明确哪种方案更符合可访问性标准。
参考代码
document.addEventListener("DOMContentLoaded", function() { // 创建手风琴所有按钮的数组 const accordionButtons = document.querySelectorAll(".eqd-accordion__button"); accordionButtons.forEach(button => { const contentId = button.getAttribute("aria-controls"); const content = document.getElementById(contentId); const contentHeight = document.getElementById(contentId + "-height").offsetHeight; // 检查手风琴面板是否展开 const isExpanded = button.getAttribute("aria-expanded") === "true"; if(isExpanded) { // 设置可见面板的高度 content.style.visibility = "visible"; content.style.height = contentHeight + "px"; } else { // 收起aria-expanded为false的面板 const contentToHide = document.getElementById(button.getAttribute("aria-controls")); if (contentToHide) { contentToHide.style.height = "0"; contentToHide.style.visibility = "hidden"; } } // 为每个按钮添加点击事件 button.addEventListener("click", function() { // 点击时检查面板是否展开 const isExpanded = button.getAttribute("aria-expanded") === "true"; // 收起所有手风琴面板 accordionButtons.forEach(btn => { // 通过aria-controls属性获取对应内容 const contentToHide = document.getElementById(btn.getAttribute("aria-controls")); btn.setAttribute("aria-expanded", "false"); if (contentToHide) { contentToHide.style.height = "0"; contentToHide.style.visibility = "hidden"; } }); // 如果点击的面板未展开,则展开它 if (!isExpanded) { button.setAttribute("aria-expanded", "true"); content.style.visibility = "visible"; content.style.height = contentHeight + "px"; const pagePosBeforeExpand = window.scrollY; window.scrollTo({ top: pagePosBeforeExpand }); } }); }); });
方案分析与结论
1. 阻止页面滚动方案
你当前使用window.scrollTo({ top: pagePosBeforeExpand })固定滚动位置的方案,从可访问性角度是安全的:
- 保持激活按钮在视野内,符合用户操作预期,点击后不会丢失操作上下文
- 完全不干扰屏幕阅读器对按钮的识别和交互,按钮始终处于焦点状态且可被正常读取
2. 模糊元素方案
模糊元素的方案需要谨慎使用:
- 若仅做视觉模糊,未改变按钮焦点状态或可访问属性,屏幕阅读器仍能正常识别交互,不会直接影响可访问性
- 但如果模糊操作伴随移除焦点、修改
aria-hidden等属性,会导致屏幕阅读器无法定位按钮,破坏操作连续性,严重影响可访问性
最优选择
优先选择阻止页面滚动的方案:
- 符合WCAG(Web内容可访问性指南)中操作上下文保持的要求
- 无额外可访问性风险,所有用户(包括屏幕阅读器使用者)的操作体验更一致
内容的提问来源于stack exchange,提问作者Natalja
相关产品推荐
相关产品推荐

