如何为多步骤表单中的单选按钮(Label)添加选中效果
单选按钮自定义选中效果实现方案

你可以通过JS监听单选框状态,动态切换选中样式,完整实现如下:
实现逻辑
- 隐藏原生单选按钮,将交互触发绑定到label元素上
- 监听单选框点击事件,先清空同组所有单选框的选中样式,再为当前选中项添加蓝色背景、白色文字样式
- 所有样式通过JS动态注入,无需额外编写独立CSS文件,符合优先使用JS实现的要求
完整修改后代码
JS代码
$(document).ready(function() { 'use strict'; // 动态注入所需样式 const customStyle = ` .form-group { position: relative; margin: 12px 0; } .form-group input[type=radio] { position: absolute; opacity: 0; pointer-events: none; } .form-group label { display: block; padding: 10px 16px; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer; transition: all 0.2s ease; } .form-group.radio-active label { background-color: #2563eb; color: #ffffff; border-color: #2563eb; } `; $('head').append(`<style>${customStyle}</style>`); // 单选/复选框点击事件 $('input[type=radio], input[type=checkbox]').on('click', function(e) { const inputName = $(this).attr('name'); // 单选框需要先清空同组其他选项的选中状态 if ($(this).is(':radio')) { $(`input[name="${inputName}"]`).parents('.form-group').removeClass('radio-active'); } // 切换当前项选中样式 $(this).parents('.form-group').toggleClass('radio-active', $(this).is(':checked')); console.log($(this).val()); $(this).parents('.test-step').next().addClass('active'); $(this).parents('.test-step').removeClass('active'); }) // 上一步按钮事件 $('.test-step .prev-btn').on('click', function(e) { $(this).parents('.test-step').prev().addClass('active'); $(this).parents('.test-step').removeClass('active'); }) })
HTML代码(单选组示例)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-group"> <input type="radio" name="calisan-sayisi" value="1 - 2" class="form-control" id="opt1"> <label for="opt1">1 - 2</label> </div> <div class="form-group"> <input type="radio" name="calisan-sayisi" value="3 - 5" class="form-control" id="opt2"> <label for="opt2">3 - 5</label> </div> <div class="form-group"> <input type="radio" name="calisan-sayisi" value="6 - 10" class="form-control" id="opt3"> <label for="opt3">6 - 10</label> </div>
内容的提问来源于stack exchange,提问作者Yağız Gürbüz
相关产品推荐
相关产品推荐

