仅带html的Bootstrap按钮组预选按钮

时间:2014-03-12 20:11:47

标签: html twitter-bootstrap

使用Bootstrap我想要一个按钮组,但预先选择了一个按钮。如果我使用下面的html,则第一个按钮被预选,但即使我点击其中一个按钮,它仍然保持活动状态。

仅使用html如何定义按钮组,并选择一个按钮,当我单击其中一个按钮时,该按钮将取消选择。

<div class="btn-group">
  <button type="button" class="btn btn-default active">Left</button>
  <button type="button" class="btn btn-default">Middle</button>
  <button type="button" class="btn btn-default">Right</button>
</div>

1 个答案:

答案 0 :(得分:6)

真的,你唯一能做的就是没有JavaScript 就是将属性autofocus="autofocus"添加到所需的元素中,如下所示:

<button type="button" class="btn btn-default" autofocus="autofocus">Left</button>

正如属性所暗示的,该按钮将自动聚焦在支持的浏览器中。如果单击另一个按钮,则将删除第一个按钮的焦点。

EXAMPLE HERE

值得注意的是.btn-default.active的样式与.btn-default:focus相同:

.btn-default:focus, .btn-default.active {
    color: #333;
    background-color: #ebebeb;
    border-color: #adadad;
}

不幸的是,当点击页面上的任何其他位置时,焦点也将被删除。如果这是一个问题,需要JavaScript来解决这个问题。解决方案是在所需元素上使用active类,然后在单击任何兄弟按钮元素时将其删除。选择将与无线电元素相互排斥。

以下是直接从Bootstrap JS documentation获取的示例。值得注意的是,需要包含Bootstrap JS文件/ jQuery。

EXAMPLE HERE

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1"> Option 1
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> Option 3
  </label>
</div>