折叠列表-需要做一个折叠按钮



我正在制作一个无序的可折叠列表。我已经创建了一个汉堡包/可折叠/手风琴菜单。但是,我想添加一个"全部展开/全部折叠"按钮在上面。有人能帮我输入密码吗?

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>

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

最简单的答案:

添加一个按钮:<button onclick="toggleExpandCollapse();">Expand/Collapse</button>

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

最后,添加如下css:.hidden {display:none;}

你完成了!

相关内容

  • 没有找到相关文章

最新更新