我试图在我的网站上有一个扩展所有按钮。我有两个级别的扩展和折叠链接,并希望有一个选项,当有人想看到所有不点击。我想我知道我需要做什么-循环所有手风琴,并设置他们显示。你能给我一些提示吗。
这是密码。请帮忙。
function ExpandAll() {
var acc = document.getElementsByClassName("accordionMain");
var i;
for (i = 0; i < acc.length; i++) {
var panel = this.Children
panel.style.display = "block";
}
}
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
button.accordion.active,
button.accordion:hover {
background-color: #ddd;
}
div.panel {
padding: 0 18px;
display: none;
background-color: white;
}
<!DOCTYPE html>
<head>
</head>
<body>
<h2>Accordion</h2>
<button onclick="ExpandAll();">Expand All</button>
<button class="accordion">Section 2</button>
<div class="panel">
<button class="accordion">Section 1</button>
<div class="panel">
<p>
content
</p>
</div>
</div>
<button class="accordion">Section 3</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</body>
</html>
最佳答案
ExpandAll()
应该是expandAll()
(可能不重要,但这让我很困扰)
确保也为按钮的onclick
更改它。
<button onclick="expandAll();">Expand All</button>
然后更改代码以不查找
acordionMain
,而是查找panel
。getElementsByClassName(X)
返回并数组。因此,您可以遍历该数组并通过JS将样式设置为display: "block"
。代码如下。<script>
function expandAll ()
{
var elements = document.getElementsByClassName("panel");
for (var i = 0; i < elements.length; i++) {
var panel = elements[i];
panel.style["display"] = "block";
}
}
</script>
编辑:
这是小提琴:https://jsfiddle.net/CraftingGamerTom/f6y96c2e/