html - 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>
解决方案
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);
});
推荐阅读
- algorithm - 如何持续获取新数据并在过程中间注入不同的东西?
- python - 调用pyodbc游标时出现线程错误
- electron - 如何在电子应用程序中实现 ngxs 托管状态的存储
- haskell - 在堆栈的 docker 中捕获 ctrl-c
- javascript - 跨度应该有 9 li
- c++ - 是否有可以在 iOS 上运行的 API 来更改现有视频的每秒帧数?
- python - 汇总计算有时会无故超时
- angular - 我在循环执行许多 http 请求时遇到了一些问题
- jquery - 使用 jquery 切换 css 转换问题
- python-3.x - 在 __getattribute__ 方法中打印出函数参数和值