活动 Bootstrap 个按钮

Active Bootstrap Buttons

我刚刚尝试使用 Bootstraps 按钮组在我的网页上显示和隐藏 div。也许我很笨,但是有人能指出正确的方向让我在单击时激活所选按钮吗?

HTML(按钮):

<div class="btn-group" role="group" aria-label="...">
     <button id="1" type="button" class="btn btn-default">Button 1</button>
     <button id="2" type="button" class="btn btn-default">Button 2</button>
     <button id="3" type="button" class="btn btn-default">Button 3</button>
</div>

JQuery:

<script>
$("#1").click(function(){
    $("#first-section").show();
    $("#second-section").hide();
    $("#third-section").hide();
});

$("#2").click(function(){
    $("#first-section").hide();
    $("#second-section").show();
    $("#third-section").hide();
});

$("#3").click(function(){
    $("#first-section").hide();
    $("#second-section").hide();
    $("#third-section").show();
});
</script>

我假设我必须在每个函数的 .show() 附近做一些事情,所以在按钮上应用活动 class。任何朝着正确方向的推动都会有很大帮助!

您可以创建一个 class 在点击时激活按钮:例如点击也许?未经测试,但应该可以正常工作

The ToggleClass method:

This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

(".btn").click(function() {
   // Instead of directly editing CSS, toggle a class
   $(".btn").removeClass("clicked");//removes classes everywhere
   $(this).toggleClass("clicked");//adds the class at the right button
});
.clicked {
   background-color: #differentcolorhere;
}

您也可以为每个按钮自动执行此操作

<script>
$("#1").click(function(){
    $("#first-section").show();
    $("#second-section").hide();
    $("#third-section").hide();

});

$("#2").click(function(){
    $("#first-section").hide();
    $("#second-section").show();
    $("#third-section").hide();

});

$("#3").click(function(){
    $("#first-section").hide();
    $("#second-section").hide();
    $("#third-section").show();
});
</script>

在您的点击事件中试试这个:

$(this).addClass('Active');

在设置活动之前,您可以像这样从所有按钮中删除 class:

$("button.btn").removeClass('Active');