jQuery accordion - how to collapse other open accordion panes when another one is opened

拟墨画扇 提交于 2021-02-16 18:38:33

问题


I have an accordion that I want to have the following functionality: when the user clicks on a link to expand, the other expanded links (if any) will collapse. I know this functionality is built in the accordion plugin, but I'm trying to avoid adding another library (jQuery UI).

EDIT: Here is the code I have right now (here it is on jsFiddle: http://jsfiddle.net/s2Jfs/2/):

    $('.accordion-toggler').addClass('toggle-plus');

    $('.accordion-toggler').click(function() {
        $this = $(this);
        if($this.hasClass('toggle-plus')) {
            $this.removeClass('toggle-plus').addClass('toggle-minus');
        } else {
            $this.removeClass('toggle-minus').addClass('toggle-plus');
        }
        $this.next('.mod-content').slideToggle();
    });

The "mod-content" class is attached to the content that should be expanded/collapsed. Right now, if you expand one item, leave it open, then click another, you have more than one expanded areas. How can I collapse other links except for the active one?


回答1:


You're making this way more complicated than it has to be. If you're simply wanting one to slide down while the others slide back up, use the following code...

$('.accordion-toggler').click(function() {
    var targetElement = $(this).next('.mod-content');
    targetElement.slideToggle();
    targetElement.siblings('.mod-content').slideUp();
});


来源:https://stackoverflow.com/questions/6946908/jquery-accordion-how-to-collapse-other-open-accordion-panes-when-another-one-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!