当我点击另一个时,请如何折叠手风琴的任何开放部分

时间:2016-11-03 00:20:50

标签: jquery css html5 twitter-bootstrap

当我点击另一个时,请如何折叠手风琴的任何开放部分?单击某个部分后,单击另一部分后它将保持打开状态。

<!DOCTYPE html>
<html>
<head>
<style>
button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}

div.panel {
    padding: 0 18px;
    display: none;
    background-color: white;
}

div.panel.show {
    display: block;
}
div.panel.collapse {
    display: block;
}


</style>
</head>
<body>

<h2>Accordion</h2>

<button class="accordion">Section 1</button>
<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>

<button class="accordion">Section 2</button>
<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>

<button class="accordion">Section 3</button>
<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>
</body>
</html>

JS

<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");            
  }
}
</script>

当我点击另一个时,请如何折叠手风琴的任何开放部分?单击某个部分后,单击另一部分后它将保持打开状态。

1 个答案:

答案 0 :(得分:0)

我为你做了一个小提琴,也许你可以检查一下我在这个问题上使用了jquery这是你想做的事吗?

$('.accordion').on('click',function(){
    if($(this).hasClass('active')){
   $(this).removeClass('active');
  $(this).next().removeClass('show');
 }else{
    $('.accordion').removeClass('active')
  $('.panel').removeClass('show')
  $(this).addClass('active');
  $(this).next().addClass('show');
}
})

https://jsfiddle.net/ktdsnnkp/1/