如何使用ES6 JavaScript切换aria-expanded属性的值
解决按钮点击切换aria-expanded属性的方案
你可以直接在原有切换类的逻辑基础上,新增对触发按钮aria-expanded属性的操作即可,以下是修改后的完整代码:
const theTrigger = document.getElementById('mobile-form-control'); const theForm = document.querySelectorAll('.l-header__mobile-form'); theTrigger.onclick = function () { // 获取当前aria-expanded的状态,注意属性值是字符串类型 const isExpanded = theTrigger.getAttribute('aria-expanded') === 'true'; // 切换属性值 theTrigger.setAttribute('aria-expanded', !isExpanded); for (const x of theForm) { x.classList.toggle('show'); } };
可选优化写法
如果你要保证表单显隐状态和aria-expanded属性完全同步,也可以直接用classList.toggle返回的布尔值来赋值,代码更简洁:
const theTrigger = document.getElementById('mobile-form-control'); const theForm = document.querySelectorAll('.l-header__mobile-form'); theTrigger.onclick = function () { for (const x of theForm) { // classList.toggle会返回切换后是否包含该类的布尔值 const isFormShown = x.classList.toggle('show'); theTrigger.setAttribute('aria-expanded', isFormShown); } };
注意事项
- 所有
aria-*属性的值默认都是字符串类型,判断状态时不要直接用Boolean()转换,需要和字符串'true'做全等比较,避免出现类型错误 - 记得在HTML的触发按钮标签上提前初始化
aria-expanded="false"属性,避免首次点击时读取到null值导致逻辑异常
内容的提问来源于stack exchange,提问作者Robert E
相关产品推荐
相关产品推荐

