You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery修改Bootstrap 3中单选按钮的颜色

修改Bootstrap 3自定义单选按钮颜色的jQuery方案

嘿,我来帮你搞定这个问题!看你的代码,你用的是带有radio-custom radio-primary类的自定义单选按钮(应该是admin-form组件的样式),这类按钮的颜色不是直接通过元素的color属性控制的,而是通过伪元素(::before、::after)的样式来实现的。下面给你两种实用的jQuery解决方案:

方案一:切换预设的主题颜色类

admin-form这类组件通常会提供多种预设的颜色类(比如radio-success、radio-danger、radio-info),你可以直接用jQuery切换这些类来快速改变颜色:

// 示例:将"Yes"单选按钮切换为危险红色(danger)样式
$('input[name="IsRemix"][value="true"]').closest('.radio-custom')
  .removeClass('radio-primary')
  .addClass('radio-danger');

// 如果需要在选中时动态切换颜色,可以结合change事件
$('input[name="IsRemix"]').on('change', function() {
  // 先移除所有单选按钮的自定义颜色类
  $('.radio-custom').removeClass('radio-danger radio-success');
  
  // 给当前选中的单选按钮添加目标颜色类
  if ($(this).val() === 'true') {
    $(this).closest('.radio-custom').addClass('radio-danger');
  } else {
    $(this).closest('.radio-custom').addClass('radio-success');
  }
});

方案二:自定义颜色(通过添加自定义类关联CSS)

如果预设类满足不了你的需求,想要完全自定义颜色,可以先在CSS里定义自定义样式,再用jQuery给目标元素添加对应的类:

首先在你的样式表中添加:

/* 自定义红色单选按钮样式 */
.radio-custom.radio-my-red::before {
  border-color: #ff4444; /* 自定义边框颜色 */
}
.radio-custom.radio-my-red.checked::after {
  background-color: #ff4444; /* 自定义选中后的填充颜色 */
}

/* 自定义蓝色单选按钮样式 */
.radio-custom.radio-my-blue::before {
  border-color: #0099cc;
}
.radio-custom.radio-my-blue.checked::after {
  background-color: #0099cc;
}

然后用jQuery来切换这个自定义类:

// 给所有IsRemix单选按钮应用自定义红色样式
$('.radio-custom.radio-primary')
  .removeClass('radio-primary')
  .addClass('radio-my-red');

// 或者在选中时切换不同自定义颜色
$('input[name="IsRemix"]').on('change', function() {
  $('.radio-custom').removeClass('radio-my-red radio-my-blue checked');
  const targetClass = $(this).val() === 'true' ? 'radio-my-red' : 'radio-my-blue';
  $(this).closest('.radio-custom').addClass(targetClass + ' checked');
});

注意点

  • 这类自定义单选按钮的选中状态是靠.checked类来控制的,所以切换颜色时别忘了同步处理这个类
  • 不要直接用jQuery.css()去修改伪元素样式,因为伪元素不属于DOM节点,jQuery无法直接操作它们,通过类关联CSS是最可靠的方式

内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:20:15