如何在具有不同背景的已检查和未检查状态下设置无线电输入的样式?

时间:2018-05-15 15:52:29

标签: html twitter-bootstrap css3 radio-button bootstrap-4

我有多个颜色选择选项,我想突出显示它们被选中的颜色

这是我的第一张图片first image

我希望将此转换为此image below

感谢您的时间和建议

1 个答案:

答案 0 :(得分:0)

您可以同样改变收音机的风格。对于选中状态,请使用 [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>

选中此codepen

更新

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

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