我正在尝试使用“全部展开”按钮。我可以使所有div标签扩展,但不能将加号切换为减号(当您一次单击加号时会发生这种情况-它会扩展并变为减号。)我认为我需要以某种方式操纵此标签{ {1}}更改其“内容”设置,但是如何?我可以用javascript吗?这是代码。请帮忙。
p.accordion:before
function expandAll() {
var elements = document.getElementsByClassName("panel");
//enter code here
for (var i = 0; i < elements.length; i++) {
var panel = elements[i];
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";
}
}
}
p.accordion {
cursor: pointer;
width: 100%;
border: none;
text-align: left;
outline: none;
transition: 0.4s;
}
p.accordion.active,
p.accordion:hover {
background-color: #ddd;
}
p.accordion:before {
content: '\002B';
float: left;
}
p.accordion.active:before {
content: "\2212";
}
div.panel {
padding: 0 18px;
display: none;
background-color: white;
}
答案 0 :(得分:1)
您已经有active
类。只需将其添加到所有p
中即可。
document.querySelector('button').addEventListener('click', expandAll)
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";
}
}
}
function expandAll() {
var elements = document.getElementsByClassName("panel");
var accordions = document.querySelectorAll('p.accordion')
for (var i = 0; i < elements.length; i++) {
var panel = elements[i];
panel.style["display"] = "block";
accordions[i].classList.add("active");
}
}
p.accordion {
cursor: pointer;
width: 100%;
border: none;
text-align: left;
outline: none;
transition: 0.4s;
}
p.accordion.active,
p.accordion:hover {
background-color: #ddd;
}
p.accordion:before {
content: '\002B';
float: left;
}
p.accordion.active:before {
content: "\2212";
}
div.panel {
padding: 0 18px;
display: none;
background-color: white;
}
<h2>Accordion</h2>
<button>Expand All</button>
<p class="accordion">Section 2</p>
<div class="panel">
<p class="accordion">Section 1</p>
<div class="panel">
<p>
content
</p>
</div>
</div>
<p class="accordion">Section 3</p>
<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>