单击另一个时,折返标签关闭标签

时间:2018-03-06 12:33:49

标签: jquery html accordion

我创建了一个手风琴,但我希望它在单击另一个时关闭标签。此时,它会打开标签,但是当单击另一个标签时,它不会关闭最后一个标签...

这是代码:

<button class="accordion">Accordion</button>
<div class="panel">Content</div>

<button class="accordion">Accordion 2</button>
<div class="panel">Content</div>

This is the code working

2 个答案:

答案 0 :(得分:1)

只是&#34;关闭&#34;点击事件中的所有手风琴页面。

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    var elems = document.getElementsByClassName("accordion");
    for(var it of elems) {
      it.classList.remove("active");
      it.nextElementSibling.style.maxHeight = null;
    }

    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  });

}

Live demo.

答案 1 :(得分:0)

在Accordion下方使用,并在html

中的链接路径上下载第一个js和css

$( "#accordion" ).accordion({event:false, active :false});

var noSections = $("#accordion h3").length-1;

$("h3").each(function (index, element)
{
    $(element).click(function()
    {
       if($(this).hasClass('ui-state-active'))
       {
           if(index < noSections)
              $("#accordion").accordion('option','active',index + 1);
           else
              $("#accordion").accordion('option','active',index - 1);
       }
       else
       {
          $("#accordion").accordion('option','active',index);
       }
   });
}); 
  
.accordionStyle{
 position: relative !important;
 width:500px !important; 
 margin: 30px auto !important;
}

.accordionStyle h3{
 padding-left:35px; 
}

p{
 font-size:12px 
}
.ui-accordion .ui-accordion-icons {
    padding-left: 2.2em;
}
.ui-accordion .ui-accordion-header {
    display: block;
    cursor: pointer;
    position: relative;
    margin: 2px 0 0 0;
    padding: .5em .5em .5em .7em;
    min-height: 0;
    font-size: 100%;
}
.accordionStyle h3 {
    padding-left: 35px;
}
.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr {
    border-top-right-radius: 4px;
}
.ui-widget-content {
    border: 1px solid #aaaaaa;
    background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;
    color: #222222;
}
<div id="accordion" class="accordionStyle">
  <h3>Accordion 1</h3>
  <div>
    <p>
    test1
    </p>
  </div>
  <h3>Accordion  2</h3>
  <div>
    <p>
   test2
    </p>
  </div>
  <link rel="stylesheet" href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>