Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

How do you make Twitter Bootstrap Accordion keep one group open?

I am trying to mimic the Outlook bar using Twitter bootstrap using the accordion and collapse plugin, so far I got the collapse and accordion working, but it presently allows for all sections to be collapsed.

I would like to limit it so that one and only one is always shown.

Here is the one I am working on: http://jsfiddle.net/trajano/SMT9D/ and I think it's somewhere along the lines of

$('#accordions').on('hide', function (event) {
  console.warn("HIDE TRIGGERED, check if trying to hide the active one if so stop");
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an easy way to do it:

Bootstrap 4

$('.accordion .btn-link').on('click', function(e) { 
  if (!$(this).hasClass('collapsed')) { 
    e.stopPropagation(); 
  } 
});

from @mr_joncollette in the comments

Bootstrap 3

JsFiddle for Bootstrap 3.

Code for Bootstrap 3:

$('.panel-heading a').on('click',function(e){
    if($(this).parents('.panel').children('.panel-collapse').hasClass('in')){
        e.stopPropagation();
    }
    // You can also add preventDefault to remove the anchor behavior that makes
    // the page jump
    // e.preventDefault();
});

The code checks if the clicked element is the one that is currently shown (by the class "in") and if it does have the "in" class, it stops the hiding process.


Deprecated Bootstrap 2

JsFiddle for Bootstrap 2.

Code for Bootstrap 2:

$('.accordion-toggle').on('click',function(e){
    if($(this).parents('.accordion-group').children('.accordion-body').hasClass('in')){
        e.stopPropagation();
    }
    // You can also add preventDefault to remove the anchor behavior that makes
    // the page jump
    // e.preventDefault();
});

Note: Be careful if you want to attach more click events on the accordion, since the e.stopPropagation() will block events that would occur after the check.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...