使用 javascript 在 true 和 false 之间切换 aria-expanded

问题描述 投票:0回答:2

我试图在单击按钮时在 true 和 false 之间切换 aria 标签。我已经尝试了几种实现,但似乎完全没有任何作用。以下是我当前正在使用的成功切换课程的内容。我如何扩展它以在 true 和 false 之间切换 aria-expanded 值?别介意,我正在从 jQuery 过渡到 ES6。

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

theTrigger.onclick = function () {
  for (const x of theForm) {
    x.classList.toggle('show');
  }
};

javascript accessibility wai-aria
2个回答
5
投票

通过简单的切换会更容易:

    x.ariaExpanded = !x.ariaExpanded;

但奇怪的是,Firefox 不支持对 DOM 属性的直接布尔访问! 🤯 https://developer.mozilla.org/en-US/docs/Web/API/Element/ariaExpanded#browser_compatibility

所以我最终得到了这样的结果:

    x.setAttribute(
      'aria-expanded', 
      `${!(x.getAttribute('aria-expanded') === 'true')}`
    );

5
投票

假设 for 循环中的

x
是您想要切换
aria-expanded
属性的元素:

theTrigger.onclick = function () {
  for (const x of theForm) {
    x.classList.toggle('show');
    x.setAttribute(
      'aria-expanded', 
      `${(x.getAttribute('aria-expanded') !== 'true').toString()}` 
    );
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.