2014-09-18 6 views
0

У меня есть серия аккордеонов, но я хочу только, чтобы один из них расширялся за раз. В настоящее время все можно открыть.Как иметь только один открытый аккордеон?

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! 
    } 
}); 
+0

я пропускаю свой HTML Markup ... Пожалуйста, сделайте JSFiddle ... – algorhythm

+0

@algorhythm обновлено – itsclarke

ответ

1

Вам просто нужно, чтобы закрыть текущий открыл один перед открытием нового.

$('.collapse-content.open') будет нацелен на действующий в настоящее время аккордеон. Если у вас есть более чем на 1 аккордеон на странице, то вам необходимо пройти дальше вверх по дереву йот, чтобы получить родительский контейнер (.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'); 
}); 
+0

Спасибо! Я знал, что это просто! – itsclarke

Смежные вопросы