我想让一个手风琴默认打开第一个面板,并且当用户单击某个元素的其他面板时,第一个面板会自动关闭,而另一个通常是打开的。 注意:我希望使用纯JavaScript而不需要任何单一框架的帮助。
<div id="accordion">
<div class="panel">
<!-- first panel -->
<div class="header">header1</div>
<div class="body">body of panel 1</div>
</div>
<div class="panel">
<!-- second panel -->
<div class="header">header2</div>
<div class="body">body of panel 2</div>
</div>
<div class="panel">
<!-- third panel -->
<div class="header">header3</div>
<div class="body">body of panel 3</div>
</div>
</div>
答案 0 :(得分:0)
这可能会给您一个想法,这个想法只是检查悬停并添加一个类,如果它退出了容器,则应该将该类添加回第一个元素
function addClass(elem){
panels.map(panel => panel.classList.remove('active'))
elem.classList.add('active');
}
function removeClass(){
this.classList.remove('active');
}
const panels = [...document.querySelectorAll('.panel')];
const container = document.querySelector('#accordion');
panels.map(panel => {
panel.addEventListener('mouseover', ()=>addClass(panel));
panel.addEventListener('mouseleave', removeClass);
})
container.addEventListener('mouseleave', ()=>addClass(panels[0]));
#accordion {
display: flex;
}
.panel {
display: flex;
border: 2px solid;
flex-direction: column;
}
.panel .body {
display: none;
}
.panel.active .body {
display: block;
}
<div id="accordion">
<div class="panel active">
<!-- first panel -->
<div class="header">header1</div>
<div class="body">body of panel 1</div>
</div>
<div class="panel">
<!-- second panel -->
<div class="header">header2</div>
<div class="body">body of panel 2</div>
</div>
<div class="panel">
<!-- third panel -->
<div class="header">header3</div>
<div class="body">body of panel 3</div>
</div>
</div>