首页 > 解决方案 > 如何在不同背景的选中和未选中状态下设置无线电输入的样式?

问题描述

我有多种颜色选择选项,我想突出显示它们被选中的任何内容

这是我的第一张图片第一张图片

在这里我想把它转换成这个下图

感谢您的时间和建议

标签: htmltwitter-bootstrapcssradio-buttonbootstrap-4

解决方案


您也可以更改收音机的样式。对于选中状态,使用 [input-selector]:checked + label:after,对于未选中状态,使用[input-selector]:not(:checked) + label:before.

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked+label,
[type="radio"]:not(:checked)+label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked+label:before,
[type="radio"]:not(:checked)+label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked+label:after,
[type="radio"]:not(:checked)+label:after {
  content: '';
  width: 12px;
  height: 12px;
  position: absolute;
  top: 3px;
  left: 3px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked)+label:after {
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked+label:after {
  -webkit-transform: scale(1);
  transform: scale(1);
}


/* To change the background color, only customize the code below*/

.red-input:not(:checked)+label:before {
  background: red;
}

.red-input:checked+label:after {
  background: black;
}

.green-input:not(:checked)+label:before {
  background: green;
}

.green-input:checked+label:after {
  background: blue;
}

.black-input:not(:checked)+label:before {
  background: black;
}

.black-input:checked+label:after {
  background: silver;
}

.silver-input:not(:checked)+label:before {
  background: silver
}

.silver-input:checked+label:after {
  background: #E6B5A3;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>
<form class="form-inline m-5">
  <div class="form-group">
    <div class="mx-2">
      
    <input type="radio" id="test1" name="radio-group" class="red-input">
    <label for="test1">Peach</label>
   </div>
    <div class="mx-2">
    <input type="radio" id="test2" name="radio-group" class="green-input">
    <label for="test2">Orange</label>
   </div>
   <div class="mx-2">
    <input type="radio" id="test3" name="radio-group" class="black-input">
    <label for="test3">Mango</label>
   </div>
   <div class="mx-2">
    <input type="radio" id="test4" name="radio-group" class="silver-input">
    <label for="test4">Lime</label>
   </div>
  </div>
</form>

检查这个代码笔

更新

要设置输入的默认背景,请使用[input-selector]:not(:checked)+label:before.

.red-input:not(:checked)+label:before {
  background: red;
}


推荐阅读