点击自身及其他按钮时无法重置aria-expanded属性的问题
问题
用原生JS实现了按钮点击交互:
- 点击按钮时,添加
form-opened类、设置aria-expanded="true"、显示隐藏的div,按钮后缀文本变为"Close info" - 点击其他按钮时,之前激活的按钮会移除
form-opened类、重置aria-expanded="false"、隐藏div,后缀文本变回"Read more"
但重复点击同一按钮时,form-opened类能正常移除、div也能隐藏,唯独aria-expanded属性始终是true,不会重置为false。
问题原因
现有JS代码的核心问题是逻辑不同步与执行顺序错误:
- 每次点击按钮时,都会先强制执行
tip.setAttribute('aria-expanded', true),把属性设为true - 后续才调用
tip.classList.toggle('form-opened')切换类,但没有同步更新aria-expanded的状态 - 代码里的
tip.classList.contains('form-opened')只是做了状态判断,没有任何实际作用,属于无效代码
当重复点击已激活的按钮时,类被toggle移除,但aria-expanded已经被提前设为true,后续没有逻辑将其改为false,导致属性与类的状态不一致。
解决方案
调整逻辑,让aria-expanded的状态与form-opened类完全同步,修改后的JS代码如下:
const tips = Array.from(document.querySelectorAll('.toggle-button')); tips.forEach((tip) => { tip.addEventListener('click', () => { // 重置其他已激活的按钮 tips .filter((f) => f !== tip) .forEach((f) => { f.setAttribute('aria-expanded', 'false'); f.classList.remove('form-opened'); }); // 切换当前按钮的状态:先判断当前是否已激活 const isExpanded = tip.classList.contains('form-opened'); // 同步更新属性与类 tip.setAttribute('aria-expanded', !isExpanded); tip.classList.toggle('form-opened'); }); });
修改说明
- 先通过类判断当前按钮的展开状态,再反向设置
aria-expanded属性(注意传字符串'true'/'false',与HTML属性值的字符串类型统一) - 移除无效的状态判断语句,简化逻辑
- 确保属性与类的状态始终保持一致,解决重复点击时的不同步问题
内容的提问来源于stack exchange,提问作者Gillian
相关产品推荐
相关产品推荐

