加上 - jQuery Accordion的减号问题

时间:2014-09-18 22:08:00

标签: javascript jquery css

当我打开并关闭相同的菜单时,加/减更新,但是当我打开一个手风琴,然后是另一个时,都有减号。

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

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

    if (accordion.hasClass('open')) {
        accordion.animate({ height: 0 }, 300).removeClass('open');
        icon.html('+');
    } else {
        icon.html('+');
        $('.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).addClass('open');
        icon.html('−');
    }
});

2 个答案:

答案 0 :(得分:1)

更改您的else子句,以便在点击折叠的手风琴时将所有图标更改为加号。

在else子句的开头使用$('.icon').html('+');代替icon.html('+');

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

    if (accordion.hasClass('open')) {
        accordion.animate({ height: 0 }, 300).removeClass('open');
        icon.html('+');
    } else {
        $('.icon').html('+');  // This used to be icon.html('+');
        $('.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).addClass('open');
        icon.html('−');
    }
});

<强> Demo

答案 1 :(得分:0)

您还可以通过将.open类添加到.collapse-group并使用以下样式来更改css图标:

.collapse-group.open .icon:after {
    content: "+";
}

这样您就可以为打开的标题和内容部分创建其他css选择器。

您还可以查看这款简单的“纯jQuery”手风琴:http://thecodeplayer.com/walkthrough/vertical-accordion-menu-using-jquery-css3