简体   繁体   中英

jQuery accordion - one open at a time

I've got a accordion working with + and - images working when the accordion is opened and closed. I'm struggling to get it to only allow one open at a time.

(function ($) {
    $.fn.accordions = function (options) {
        return this.each(function () {
            var titleBar = $('.title', this),
                content = $('.content', this),
                img = $('<span class="arrow" />'),
                isClosed = content.hasClass('content');

            img.addClass((isClosed) ? 'upArrow' : 'downArrow');

            titleBar.append(img).on('click', function () {
                var parent = $(this).parents('.accordion'),
                    arrow = $('.arrow', this),
                    content = $('.content', parent);

                $(this).toggleClass('no-border');
                if (arrow.hasClass('upArrow')) {
                    content.slideDown(500);
                    arrow.removeClass('upArrow').addClass('downArrow');
                } else {
                    content.slideUp(500);
                    arrow.addClass('upArrow').removeClass('downArrow');
                }
            });
        });
    };

}(jQuery));

<script type="text/javascript">
$(function() { 
    $('.accordion').accordions()
});
</script>

Below is the HTML.

<div class="accordion">
  <div class="title">
       Title goes here
  </div>
  <div class="content">
           Content here
  </div>
</div>

For a self-written accordion the best way to achieve this is by going after these steps:

  1. on click event close all content fields
  2. get the reference to the element with $(this)
  3. open the content field you clicked

Edit: If you have the possibility, use jQuery UI with the Accordion Widget .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM