在Bootstrap的btn-group中预先切换一个按钮?

Ric*_*ard 17 twitter-bootstrap

我想在Bootstrap中设置一个选中的按钮btn-group:

<div class="btn-toolbar">
 <div class="btn-group">
  <button type="button" class="btn btn-default">5</button>
  <button type="button" class="btn btn-default">6</button>
  <button type="button" class="btn btn-default">7</button>
 </div>
 <div class="btn-group">
  <button type="button" class="btn btn-default">8</button>
 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我如何预先选择选项5?这个答案表明我可以active在按钮上添加类,这确实最初起作用,但是然后单击其他按钮不会停用该按钮,正如我所料.

这是一个小提琴:http://bootply.com/90490

这是active应用类的另一个小提琴,显示为什么它不是正确的解决方案:http://bootply.com/90491 - 单击任何其他按钮,按钮5仍然保持活动状态.

Eir*_*son 16

假设您希望每个按钮组有一个选择,并且您已经包含了引导程序JavaScript文件,那么以下内容应该可以正常工作.

标记

<div class="btn-toolbar">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default"><input type="radio" name="options" id="option5">5</label>
        <label class="btn btn-default"><input type="radio" name="options" id="option6">6</label>
        <label class="btn btn-default"><input type="radio" name="options" id="option7">7</label>
    </div>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default"><input type="radio" name="options" id="option8">8</label>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$(document).ready(function() {
    $(".btn").first().button("toggle");
});
Run Code Online (Sandbox Code Playgroud)

例如,如果您想要预切换第三个按钮,可以使用切片功能,如下所示:

$(".btn").slice(2,3).button("toggle");
Run Code Online (Sandbox Code Playgroud)

或者,您可以为按钮分配标识符.

这是我的小提琴:http://bootply.com/90501

  • 注意:您还可以在默认情况下选择的任何输入上使用`checked ="checked"属性.包装器标签也必须标记为`.active`,因此CSS是正确的. (2认同)

Jon*_*ith 7

我正在寻找预切换按钮的答案,并找到了这个SO.它们似乎都有点困难,我找到了BootStrap 4复选框按钮的链接,这给了我一些关于BootStrap 3如何工作的提示.我认为,我的解决方案更简单,因为它可以在html中预先编写.解决方案如下:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-default active">
        <input type="radio" checked>5
    </label>
    <label class="btn btn-default">
        <input type="radio">6
    </label>
    <label class="btn btn-default">
        <input type="radio">7
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

正如我所说,这是由BootStrap 4文档提示但在BootStrap 3上有效.重要的部分是:

  1. 将data-toggle="buttons"在btn-groupDIV.
  2. 该active标签5类.
  3. 在checked对<input type="radio">5.

我希望这有助于其他人.