首页 > 解决方案 > HTML 引导按钮切换

问题描述

单击组中的按钮时,我试图取消按钮组中的其他按钮。例如,当一个人单击“E”时,它会打开 E 按钮并关闭其他按钮。

我正在为多个不同的按钮组执行此操作,但是每个按钮组都应该能够激活一个单独的按钮,是否也可以使其以这种方式工作?

<div class="btn-group btn-group-toggle">

  <button class="btn btn-secondary acroTrained" data-toggle="buttons" autocomplete="off"> T </button>


  <button class="btn btn-secondary acroExpert" data-toggle="buttons" autocomplete="off"> E </button>


  <button class="btn btn-secondary acroMaster" data-toggle="buttons" autocomplete="off"> M </button>


  <button class="btn btn-secondary acroLegendary" data-toggle="buttons" autocomplete="off"> L </button>

</div>

标签: htmltwitter-bootstrapbuttontogglebuttongroup

解决方案


Bootstrap 5 已经具有该功能,您可以在文档的这一部分阅读更多信息:https ://getbootstrap.com/docs/5.0/components/button-group/#checkbox-and-radio-button-groups

let radios = document.querySelectorAll('.btn-group.btn-group-unselectable input[type="radio"]');

radios.forEach(radio => {
  radio.addEventListener('click', function(e) {
    if (this.getAttribute('data-previous-value') == 'true') {
      e.target.checked = false;
    } else {
      radios.forEach(radio => {radio.setAttribute('data-previous-value', false)});
    }
    
    this.setAttribute('data-previous-value', e.target.checked);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>


<div class="btn-group btn-group-unselectable" role="group" aria-label="Basic radio toggle button group">
  <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked>
  <label class="btn btn-outline-primary" for="btnradio1">T</label>

  <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio2">E</label>

  <input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio3">M</label>
  
    <input type="radio" class="btn-check" name="btnradio" id="btnradio4" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio4">L</label>
</div>

编辑

您可以使用一些 JavaScript 代码来执行此操作,您需要在单击单选按钮时在元素上存储一个临时值,因为每次单击单选按钮时它都会设置为选中,因此我们需要知道选中属性的先前状态所以当我们再次点击时,我们可以知道按钮是否是checked(活动的),如果是,我们设置为checked = false.

另外,我将类添加.btn-group-unselectable.btn-group元素。

这是此代码的JQuery版本:

$('.btn-group.btn-group-unselectable input[type="radio"]').click(function(e) {
    if($(this).attr('data-previous-value') == 'true'){
        e.target.checked = false
    } else {
        $('input[type="radio"]').attr('data-previous-value', false);
    }

    $(this).attr('data-previous-value', e.target.checked);
});


推荐阅读