如何实现按钮状态切换?点击指定按钮时其余对应按钮自动关闭
实现Checkbox互斥切换功能
需求说明
- 点击第3个checkbox按钮时,第1个和第2个checkbox按钮自动切换为关闭状态
- 点击第2个checkbox按钮时,第1个和第3个checkbox按钮自动切换为关闭状态
解决方案
利用jQuery监听checkbox点击事件,根据点击目标控制其他checkbox的状态,以下是完整实现代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> div { color: red; } /* 滑动开关样式,匹配示例图效果 */ .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { transform: translateX(26px); } .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } </style> <table class="tg"> <thead> <tr> <th class="tg-6nwz"></th> <th class="tg-baqh">Colum 1</th> <th class="tg-baqh">Colum 2</th> <th class="tg-baqh">Colum 3</th> </tr> </thead> <tbody> <tr> <td class="tg-c3ow">TH01</td> <td class="tg-c3ow smtp-01"> <label class="switch"> <input type="checkbox" checked="checked" class="checkbox-item"> <span class="slider round"></span> </label> </td> <td class="tg-c3ow smtp-02"> <label class="switch"> <input type="checkbox" checked="checked" class="checkbox-item"> <span class="slider round"></span> </label> </td> <td class="tg-c3ow smtp-03"> <label class="switch"> <input type="checkbox" checked="checked" class="checkbox-item"> <span class="slider round"></span> </label> </td> </tr> </tbody> </table> <div id="log"></div> <script> $(document).ready(function() { $('.checkbox-item').on('click', function() { // 获取当前checkbox的序号(对应第1/2/3个) const index = $(this).closest('td').index() - 1; if (index === 1) { // 点击第2个,关闭第1、3个 $('.checkbox-item').eq(0).prop('checked', false); $('.checkbox-item').eq(2).prop('checked', false); } else if (index === 2) { // 点击第3个,关闭第1、2个 $('.checkbox-item').eq(0).prop('checked', false); $('.checkbox-item').eq(1).prop('checked', false); } }); }); </script>
代码说明
- 给所有checkbox添加统一类名
.checkbox-item,简化选择器定位 - 通过
closest('td').index()获取当前checkbox所在单元格的索引,减去1得到对应的checkbox序号 - 使用
prop('checked', false)将目标checkbox设置为关闭状态 - 补充滑动开关样式CSS,让控件显示效果与示例图一致
内容的提问来源于stack exchange,提问作者donald.sys
相关产品推荐
相关产品推荐

