怎么只有一个开放的手风琴?

时间:2014-09-18 20:17:18

标签: javascript jquery

我有一系列手风琴,但我只想让一个手风琴一次扩展。目前,所有都可以打开。

http://codepen.io/anon/pen/uaytq

$('.collapse-toggle').click(function (e) {
    var that = $(this).parent();
    var accordion = that.find('.collapse-content');

    if (accordion.hasClass('open')) {
        accordion.removeClass('open');
        accordion.animate({ height: 0 }, 300);
    } else {
        var currentHeight = accordion.height(); //save current height
        accordion.css('height', 'auto');        //temporary switch height to auto
        var autoHeight = accordion.height();    //get auto height
        accordion.css('height', currentHeight); //switch back to current height
        accordion.animate({ height: autoHeight }, 300); //animate that beautiful thing
        accordion.addClass('open');             //let the people know!
    }
});

1 个答案:

答案 0 :(得分:1)

您只需关闭当前打开的那个,然后再打开一个。

$('.collapse-content.open')将针对目前开放的手风琴。如果你在页面上有超过1个手风琴,那么你需要进一步遍历dom树以获得当前手风琴的父容器(在这种情况下为.wrap

if (accordion.hasClass('open')) {
    accordion.removeClass('open');
    accordion.animate({ height: 0 }, 300);
} else {
    $('.collapse-content.open').animate({ height: 0 }, 300).removeClass('open');
    var currentHeight = accordion.height(); //save current height
    accordion.css('height', 'auto');        //temporary switch height to auto
    var autoHeight = accordion.height();    //get auto height
    accordion.css('height', currentHeight); //switch back to current height
    accordion.animate({ height: autoHeight }, 300); //animate that beautiful thing
    accordion.addClass('open');             //let the people know!
}

http://codepen.io/anon/pen/ufskl

我不确定你的开放课程是做什么的,但是如果它稍后有一些css含义你需要在手风琴项目结束时删除它然后执行此操作

$('.collapse-content.open').animate({ height: 0 }, 300, function() {
    $(this).removeClass('open');
});