javascript - 如何在页面加载时保持手风琴面板打开,但之后保持其可折叠性?
问题描述
对于我的手风琴菜单,我很难弄清楚如何在浏览器加载时保持手风琴面板打开。我试过删除溢出:隐藏;对于面板,但我遇到了错误。我希望能够在浏览器加载时打开我的面板,但之后让用户打开/关闭链接。
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";
}
});
}
这是我的 Codepen。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";
}
});
}
如您所见,我所做的只是为第一个元素展开手风琴。我复制并粘贴了事件侦听器将执行的相同代码,而是在启动时直接将其附加到第一个元素。这也有助于保持可折叠性,因为添加了事件侦听器,而与其他代码无关。
希望这可以帮助!
推荐阅读
- python - 在单个模型的多个模型中使用外键时出现 django 错误
- php - PHP Array 如何使所有数组具有相同的长度
- angular - 如何以角度打印HttpRequest标头
- amazon-cloudformation - 无服务器框架 - 获取 API 网关 URL 以用于测试
- qt - 组合框qml的动态翻译
- pandas - 如何计算特定列的滚动平均值并需要打印滚动平均值以及日期
- android - 如何在 Android P (API 28) 中在外部 SD 卡上打开数据库
- angular - 使用服务的可重用组件之间的通信
- angular - Angular Material Snackbar 未正确显示
- java - JPA OneToOne,外键在 Spring Boot 上为空