如何在页面加载时保持手风琴面板打开,但之后保持其可折叠性?



对于我的手风琴菜单,我很难弄清楚如何在浏览器加载时保持手风琴面板打开。我尝试删除溢出:隐藏;对于面板,但我遇到了错误。我希望能够在浏览器加载时打开我的面板,但让用户在之后打开/关闭链接。

.HTML

<div class="sideMenu">
<div class="logo">TS<div>
<div class="smallSpacer"></div>
<div class="accordion">code</div>
<div class="panel">
<p>uhn redesign </p>
<p>180 websites </p>
</div>
<div class="bigSpacer"></div>
<div class="accordion">design</div>
<div class="panel">
<p>gigloo </p>
<p>space is the place</p>
<p>tyler the creator </p>
<p>nike concepts</p>
<p>portraits/fashion</p>
</div>
<div class="bigSpacer"></div>
<div class="accordion">personal</div>
<div class="panel">
<p>product</p>
<p>animations</p>
<p>comics</p>
</div>
</div>

.CSS

body{
font-family: 'Roboto Mono', monospace;
}
.sideMenu{
background-color:black;
width:250px;
height:100%;
position:fixed;
margin:20px;
text-align:center;
}
.logo{
color:white;
}
.smallSpacer{
margin-bottom:15px;
}
.bigSpacer{
margin-bottom:20px;
}
.accordion {
color: white;
cursor: pointer;
transition: 0.4s;
font-weight:500;
}
.active, .accordion:hover {
}
.panel {
font-weight:300;
max-height: 0;
overflow: hidden;
transition: max-height 0.1s ease-out;
}

JAVASCRIPT

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}

这是我的编程笔。https://codepen.io/taniasharma98/pen/KKwQXBK

这是我的解决方案:

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
//this is where magic happens
if(i==0){
acc[0].classList.toggle("active");
var panel = acc[0].nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}  
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}

正如你所看到的, 我所做的只是扩展第一个元素的手风琴. 我已经复制并粘贴了事件侦听器将执行的相同代码,而是在启动时直接将其附加到第一个元素。这也有助于保持可折叠性,因为无论其他代码如何,都添加了事件侦听器。

希望这有帮助!

最新更新