HTML Bootstrap 按钮切换

问题描述

我试图在单击组中的按钮时取消切换按钮组中的其他按钮。例如,当一个人点击“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>

解决方法

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

 private readonly IMyAccountService _myAccountService;
        public Startup(IConfiguration configuration,IMyAccountService AccountService)
        {
            Configuration = configuration;
            _myAccountService = AccountService
        }
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);
  });
});

编辑

你可以用一些 JavaScript 代码来做到这一点,你需要在点击单选按钮时在元素上存储一个临时值,因为每次点击单选按钮时它都会被设置为选中状态,所以我们需要知道之前的状态选中属性,所以当我们再次点击时,我们可以知道按钮是否为 <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>(活动),如果是,我们设置为 checked

此外,我将类 checked = false 添加到 .btn-group-unselectable 元素。

这是此代码的 JQuery 版本:

.btn-group