Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Bootstrap 3 btn-group Lose Active Class when Click any where on the Page

CAn you please take a look at following Demo and let me know why btn-group is loosing Active class whenever I click any where on the page. I was expecting the btn-group toggle only between each other? did I do any thing wrong here?

<div class="container">
    <div class="well">
        <div class="btn-group">
            <button type="button" class="btn btn-default" id="regi1">Left</button>
            <button type="button" class="btn btn-default" id="regi2">Middle</button>
            <button type="button" class="btn btn-default" id="regi3">Right</button>
        </div>
     </div>
</div>
question from:https://stackoverflow.com/questions/20870671/bootstrap-3-btn-group-lose-active-class-when-click-any-where-on-the-page

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

1 Answer

0 votes
by (71.8m points)

So, (as mentioned in the comments) that gray fill you see isn't actually an active class being applied - it's the focus selection behaviour of that particular Bootstrap button element. (Like the dotted outline of a hyperlink.) Try pressing Tab after clicking a button, and you should see the focus selection change.

One way to get the behaviour you want is to apply the active class yourself, and have a bit of jQuery to swap the active class when clicking a button in the group. Here's what the snippet might look like:

$(".btn-group > .btn").click(function(){
    $(this).addClass("active").siblings().removeClass("active");
});

The code above removes the active class from all .btn elements in the .btn-group, then applies the active class to the one that was just clicked.

Here's a JSFiddle demo to show you what this achieves (note that I coded the first button to have the active class in the HTML to start with). If this isn't what you were looking for, let me know and I'll be happy to help further. Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...