Toggle an Accordion with JQuery

[亡魂溺海] 提交于 2019-11-30 20:13:07

问题


I had an accordion given to me that is not toggling each tab open and close. It only closes the tab when another title is selected, but I'd like the ability for the user to close it on click as well. I'm not sure how to edit this Jquery to allow this to happen.

jQuery("ul.gdl-accordion li").each(function(){
    jQuery(this).children(".accordion-content").css('height', function(){ 
        return jQuery(this).height(); 
    });
    if(jQuery(this).index() > 0){
        jQuery(this).children(".accordion-content").css('display','none');
    }else{
        jQuery(this).find(".accordion-head-image").addClass('active');
    }       

    jQuery(this).children(".accordion-head").bind("click", function(){
        jQuery(this).children().addClass(function(){
            if(jQuery(this).hasClass("active")) return "";
            return "active";
        });
        jQuery(this).siblings(".accordion-content").slideDown();
        jQuery(this).parent().siblings("li").children(".accordion-content").slideUp();          jQuery(this).parent().siblings("li").find(".active").removeClass("active");
    });
});

I'm assuming it's somewhere in the .click function, in that if statement... but I'm not sure why.

I'm also not sure why it is defaulting the first tab as open... is there a way to modify that as well?

http://jsfiddle.net/FKAAM/

Any advice is greatly appreciated. Many thanks SO.


回答1:


Use slideToggle() instead:

jQuery(this).siblings(".accordion-content").slideDown();

jQuery(this).siblings(".accordion-content").slideToggle();

http://jsfiddle.net/FKAAM/4/




回答2:


here's the acordion link and full jQuery code:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  $(".panel-heading").click(function() {
    $(this).parent().toggleClass('active').find('.panel-body').slideToggle('fast');
    $(".panel-heading").not(this).parent().removeClass('active').find('.panel-body').slideUp('fast');
  });
});



回答3:


Add:

collapsible: true

to your accordion options, then users will be able to click to close it.

(jQuery UI Accordion: http://jqueryui.com/accordion/)




回答4:


I will suggest you to use jQuery accordion

$(function() {
        $( "#accordion" ).accordion({
            collapsible: true
        });
    });

Check the example here. I guess this is what you needed.



来源:https://stackoverflow.com/questions/14202010/toggle-an-accordion-with-jquery

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