【问题标题】:Collapsible List - Need to make a collapse all button可折叠列表 - 需要制作一个全部折叠按钮
【发布时间】:2021-08-29 08:28:44
【问题描述】:

我正在制作一个可折叠的无序列表。我已经创建了一个汉堡包/可折叠/手风琴菜单。但是,我想在顶部添加一个“全部展开/全部折叠”按钮。有人可以帮我写代码吗?

function expandCollapse() {
  var theHeaders = document.querySelectorAll('.expandCollapse h2'),
    i;

  for (i = 0; i < theHeaders.length; i++) {

    var thisEl = theHeaders[i],
      theId = 'panel-' + i;

    var thisTarget = thisEl.parentNode.querySelector('.panel');

    if (!thisTarget) {
      continue;
    }

    // Create the button
    thisEl.innerHTML = '<button aria-expanded="false" aria-controls="' + theId + '">' + thisEl.textContent + '</button>';

    // Create the expandable and collapsible list and make it focusable
    thisTarget.setAttribute('id', theId);
    thisTarget.setAttribute('hidden', 'true');
  }

  // Make it click
  var theButtons = document.querySelectorAll('.expandCollapse button[aria-expanded][aria-controls]');

  for (i = 0; i < theButtons.length; i++) {

    theButtons[i].addEventListener('click', function(e) {
      var thisButton = e.target;
      var state = thisButton.getAttribute('aria-expanded') === 'false' ? true : false;

      thisButton.setAttribute('aria-expanded', state);

      document.getElementById(thisButton.getAttribute('aria-controls')).toggleAttribute('hidden', !state);

    });
  }
}
expandCollapse();
<div class="expandCollapse">
  <section id="teams">
    <h2>Fruits</h2>
    <div class="panel">
      <ul>
        <li>
          <a href="bio/bio1.html"> Mango</a>
        </li>
      </ul>
    </div>
  </section>
  <section>
    <h2>Ghadarite</h2>
    <div class="panel">
      <ul>
        <li>
          <a href="bio/bio2.html">Potato(c. 1864-1928)</a>
        </li>
        <li>
          <a href="bio/bio3.html">Onions(c. 1884-1962)</a>
        </li>
        <li>
          <a href="bio/bio4.html"> Pepper (1886-1921)</a>
        </li>
        <li>
          <a href="bio/bio5.html">Gobind Behary Lal (1889-1982)</a>
        </li>
      </ul>
    </div>
  </section>
</div>

假设我在列表顶部添加了一个按钮,我如何编写代码来定义按钮的功能,以便它展开所有折叠的面板或折叠所有展开的面板?

【问题讨论】:

标签: javascript html accordion hamburger-menu collapsibletree-r


【解决方案1】:

最简单的答案:

添加按钮:&lt;button onclick="toggleExpandCollapse();"&gt;Expand/Collapse&lt;/button&gt;

添加这个JS:
function toggleExpandCollapse() { document.querySelectorAll('.panel').forEach(function(el) { el.classList.toggle('hidden'); }); }

最后,添加这个 css: .hidden {display:none;}

你就完成了!

【讨论】:

  • 我遵循了确切的步骤,但是当我单击按钮时,我的整个列表都被隐藏了(包括标题)
  • @Sasha 我已经编辑了答案,请再看一遍。
  • 太好了,这确实折叠了我打开的两个/三个列表项。但是仍然有两个问题。当我单击它以展开所有列表项时,它只会打开折叠的列表项(我之前打开的两个/三个)。另一个是按钮是三角形的子弹,当列表展开时会改变角度。如果我单击展开/折叠按钮,它不会更改按钮,因为它可能只是隐藏文本
  • @Sasha 您可以编辑现有代码以切换类“.hidden”。
猜你喜欢
  • 2018-12-24
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 2017-02-17
  • 2019-10-29
  • 2021-05-01
相关资源
最近更新 更多