为手风琴打开/关闭添加缓动效果

时间:2016-01-06 00:26:49

标签: javascript jquery accordion transition

我是JS的新手,但我想要一个非常简单的手风琴,所以我建了一个。出于某种原因,我在尝试为其打开/关闭添加缓动效果时感到茫然。任何帮助将非常感激。谢谢!

CodePen of Accordion

js code:

(function(){
// This class will be added to the expanded item
var activeItemClass = 'accordion-expanded';
var accordionItemSelector = '.accordion-section';
var toggleSelector = '.accordion-head';

$(toggleSelector).on('click', function() { 

    $(this)
        .closest(accordionItemSelector) // go up to the accordion item element
        .toggleClass(activeItemClass)
            .siblings()
            .removeClass(activeItemClass);
});

})();

2 个答案:

答案 0 :(得分:0)

由于您正在使用jQuery,为什么不这样做:

var accordionItemSelector = '.accordion-body';
var toggleSelector = '.accordion-head';

$(toggleSelector).on('click', function() { 
  if (!$(this).next(accordionItemSelector).is(":visible"))
    $(toggleSelector).not($(this)).next(accordionItemSelector).slideUp();
  $(this).next(accordionItemSelector).slideToggle();   
});

UPDATED PEN

答案 1 :(得分:0)

以下是手风琴的工作代码: -

$(document).ready(function(){
 $('.item').click(function (){
   if($(this).next('.item-data').css('display') != 'block'){
     $('.active').slideUp('fast').removeClass('active');
     $(this).next('.item-data').addClass('active').slideDown('slow');
    } else {
     $('.active').slideUp('fast').removeClass('active');
    }
 });
});   

和HTML

<div class='container'>
<div class='item'>Item 1</div>
<div class='item-data'>
    <div>
        This is the content for Accordion 1
    </div>
</div>
<div class='item'>Item 2</div>
<div class='item-data'>
    <div>
        This is the content for Accordion 2
    </div>
</div>
<div class='item'>Item 3</div>
<div class='item-data' >
    <div>
        This is the content for Accordion 3
    </div>
</div>
<div class='item'>Item 4</div>
<div class='item-data' >
    <div>
        This is the content for Accordion 4
    </div>
</div>

CSS

<style type="text/css">
.container
{
    display:block;
    width: 500px;
    height : auto ;
    margin: 0 auto;
}
.item
{
    display : block;
    width : inherit ;
    height : 40px;
    line-height : 40px;
    background : #555 ;
    border: 1px solid #000 ;
    cursor: pointer;
    color: #fff;
}
.item-data
{
    display : none ;
    width : inherit ;
    height : auto ;
    border: 1px solid #ccc;
}
.active {
    background : #eee ;
    color : #000 ;
}
.item-data div{
    margin: 30px;
}
</style>