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

如何用JavaScript切换aria-expanded属性的true和false值(jQuery转ES6)

实现方案

完整修改后代码

const theTrigger = document.getElementById('mobile-form-control');
const theForm = document.querySelectorAll('.l-header__mobile-form');

theTrigger.onclick = function () {
  // 切换触发按钮的aria-expanded属性
  const currentExpanded = theTrigger.getAttribute('aria-expanded') === 'true';
  theTrigger.setAttribute('aria-expanded', !currentExpanded);

  // 保留原有切换class的逻辑
  for (const x of theForm) {
    x.classList.toggle('show');
    // 若需要给表单元素也同步aria-expanded属性,取消下方注释即可
    // x.setAttribute('aria-expanded', !currentExpanded);
  }
};

逻辑说明

  • 原生JS操作DOM属性可以用getAttribute()和setAttribute(),等效于你之前用jQuery的$().attr()读写属性的能力
  • 切换逻辑和你用classList.toggle()切换类名的逻辑完全一致:先读取当前aria-expanded的属性值,转成布尔值之后取反,再写回元素即可
  • 按照无障碍规范,aria-expanded属性默认是绑定在触发交互的按钮元素上的,按需选择是否给表单元素同步该属性即可

注意事项

记得在HTML的触发按钮标签里提前加初始的aria-expanded属性,默认收起就写aria-expanded="false",默认展开就写aria-expanded="true",符合无障碍规范的同时也能避免首次读取属性拿到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:04