簡體   English   中英

使用 javascript 在真假之間切換 aria-expanded

[英]Toggle aria-expanded between true and false with javascript

當單擊按鈕時,我試圖在 true 和 false 之間切換 aria 標簽。 我已經嘗試了幾個似乎完全沒有做任何事情的實現。 以下是我目前正在使用的成功切換課程的內容。 如何擴展它以在真假之間切換 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');
  }
};

假設你的 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' 
        ? 'false' 
        : 'true'
    );
  }
};

使用簡單的切換會更容易:

    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')}`
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM