Перед открытием свернутого div ваш код должен закрыть все открытые div.
// toggle collapse of specified content
function toggleContent(content) {
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + 'px';
}
}
// collapse all open content
function collapseAllOpenContent() {
const colls = document.getElementsByClassName('collapsible');
for (const coll of colls) {
if (coll.classList.contains('active')) {
coll.classList.remove('active');
toggleContent(coll.nextElementSibling);
}
}
}
Рабочий пример:
// toggle collapse of specified content
function toggleContent(content) {
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + 'px';
}
}
// collapse all open content
function collapseAllOpenContent() {
const colls = document.getElementsByClassName('collapsible');
for (const coll of colls) {
if (coll.classList.contains('active')) {
coll.classList.remove('active');
toggleContent(coll.nextElementSibling);
}
}
}
const colls = document.getElementsByClassName('collapsible');
for (const coll of colls) {
coll.addEventListener('click', function() {
if (!this.classList.contains('active')) {
collapseAllOpenContent();
}
this.classList.toggle('active');
toggleContent(this.nextElementSibling);
});
}
.collapsible {
background-color: #fff;
color: #555;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active,
.collapsible:hover {
background-color: #fff;
}
.collapsible:after {
content: '\002B';
color: #555;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #fff;
}
<button type="button" class="collapsible">BUTTON</button>
<div class="content">
<p style="padding: 20px 0;">CONTENT</p>
</div>
<button type="button" class="collapsible">BUTTON</button>
<div class="content">
<p style="padding: 20px 0;">CONTENT</p>
</div>
<button type="button" class="collapsible">BUTTON</button>
<div class="content">
<p style="padding: 20px 0;">CONTENT</p>
</div>