我正在制作一个可折叠的无序列表。我已经创建了一个汉堡包/可折叠/手风琴菜单。但是,我想在顶部添加一个“全部展开/全部折叠”按钮。有人可以帮我写代码吗?
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>
假设我在列表顶部添加了一个按钮,我如何编写代码来定义按钮的功能,以便它展开所有折叠的面板或折叠所有展开的面板?