打开时关闭所有 jQuery 个手风琴

Close all jQuery Accordions on open

我在不同位置的页面上使用多个单独的手风琴。 如果我打开一个手风琴选项卡,所有其他“独立”手风琴都应该关闭。

如您所见: jsfiddle

example at jsfiddle

如果我打开“SECOND Accordion - Section x”,“First Accordion”中的所有部分都应该折叠起来。我需要通用代码,所以 ALL OTHER 应该关闭。

提前致谢!

下面的代码片段可以帮助您实现您想要的

$(function() {
  $(".accordion").accordion({
    heightStyle: "content",
    collapsible: true,
    active: false,
    beforeActivate: function( event, ui ) { 
        $(".ui-accordion-content").slideUp(1000);
    }
  });
});

尝试下面的可运行示例。

我添加了第三个手风琴以查看行为。 3个手风琴中只有一个会激活,其他的都会崩溃。

$( function() {
    $( ".accordion" ).accordion({
      heightStyle: "content",
      collapsible: true,
      active: false
    });

    $('.accordion').click(function() {
      // Get all the accordions
      let accordions = $('.accordion');

      // Remove the clicked accordion
      accordions.splice($('.accordion').index($(this)), 1);
      
      // Deactivate the other accordions
      $(accordions).accordion('option', 'active', false);
    });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="accordion">
    <h3>First Accordion - Section 1</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
    <h3>First Accordion - Section 2</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
</div>

<hr>
Some other content
<hr>

<div class="accordion">
    <h3>SECOND Accordion - Section 1</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
    <h3>SECOND Accordion - Section 2</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
</div>

<hr>
Even MORE content
<hr>

<div class="accordion">
    <h3>3rd Accordion - Section 1</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
    <h3>3rd Accordion - Section 2</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
</div>