You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:24:05