Home > Web Front-end > CSS Tutorial > How to change the color of radio button using css (code attached)

How to change the color of radio button using css (code attached)

不言
Release: 2018-10-12 16:59:21
forward
10277 people have browsed it

The content of this article is about the method of changing the color of the radio button using css (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Have you ever been asked by the salesperson, "Can you change the color of this radio button! Let it match the theme color!", and then you suffered from the fact that the native does not support changing the color, and finally you were forced to make a makeshift one by yourself. use. If we abandon input[type=radio] and develop a new one, we find that it is very cumbersome to simulate selected, unselected, unavailable and other states, and it is even more annoying when it involves radio button groups. In fact, we can use label, ::before, : checked and tabindex, and then adding a small amount of JavaScript script can simulate a richer style "native" radio button. Let’s try it together!

Understand the radio button box

Since our goal is to change the color of the radio button box and other appearance features and behaviors are consistent with the original radio button box, then we You must first understand the original appearance characteristics and behaviors of the radio button.
1.Appearance features
1.1.Normal style

margin: 3px 3px 0px 5px;
border: none 0;
padding: 0;
box-sizing: border-box;
display: inline-block;
line-height: normal;
position: static;
Copy after login

Note: We must ensure that the layout characteristics are consistent with the original appearance, otherwise there is a high chance that the replacement with a custom radio button will affect The overall layout eventually resulted in being forced to adjust the layout characteristics of other elements to achieve overall coordination, thereby expanding the scope of modification.

1.2. Styles that get focus

outline-offset: 0px;
outline: -webkit-focu-ring-color auto 5px;
Copy after login

Note: The style that gets focus here only takes effect through the Tab key on the keyboard. If you click with the mouse, although the radio button has gained focus, the above style will not work. will not take effect.

1.3. Set to disabled style

color: rgb(84, 84, 84);
Copy after login

2. Behavioral characteristics
The behavioral characteristics of the radio button are obviously selected or not, and the change event of the selected state, so we must Keep providing change events externally.
It is also worth noting that when the radio button gets focus through the Tab key on the keyboard, and then presses the Space key, the radio button will be selected.

With the above understanding, we can start coding!

Stop talking nonsense and code

How to change the color of radio button using css (code attached)

##In the above picture, the left side is the native radio button, and the right side On the side is our custom radio button. From top to bottom, the styles are

unselected, selected, focused and disabled.

CSS part

label.radio {
  /* 保证布局特性保持一致 */
  margin: 3px 3px 0px 5px;
  display: inline-block;
  box-sizing: border-box;

  width: 12px;
  height: 12px;
}

.radio__appearance{
  display: block; /* 设置为block则不受vertical-align影响,从而不会意外影响到.radio的linebox高度 */
  position: relative;
  box-shadow: 0 0 0 1px tomato; /* box-shadow不像border那样会影响盒子的框高 */
  border-radius: 50%;
  height: 90%;
  width: 90%;
  text-align: center;
}
label.radio [type=radio] + .radio__appearance::before{
  content: "";
  display: block;
  border-radius: 50%;
  width: 85%;
  height: 85%;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  transition: background .3s;
}
label.radio [type=radio]:checked + .radio__appearance::before{
  background: tomato;
}
label.radio [type=radio][disabled] + .radio__appearance{
  opacity: .5;
}
label.radio:focus{
  outline-offset: 0px;
  outline: #999 auto 5px;
}
/* 通过鼠标单击获得焦点时,outline效果不生效 */
label.radio.clicked{
  outline: none 0;
}
/* 自定义单选框的行为主要是基于原生单选框的,因此先将原生单选框隐藏 */
label.radio input {
  display: none;
}
Copy after login
HTML part

<!-- 未选中状态 -->
<label>
  <input>
  <i></i>
</label>

<br>

<!-- 选中状态 -->
<label>
  <input>
  <i></i>
</label>

<br>

<!-- disabled状态 -->
<label>
  <input>
  <i></i>
</label>
Copy after login
JavaScript part

var radios = document.querySelectorAll(".radio")
radios.forEach(radio => {
  // 模拟鼠标点击后:focus样式无效
  radio.addEventListener("mousedown", e => {
    var tar = e.currentTarget
    tar.classList.add("clicked")
    var fp = setInterval(function(){
      if (document.activeElement != tar){
        tar.classList.remove("clicked")
        clearInterval(fp)
      }
    }, 400)
  })
  // 模拟通过键盘获得焦点后,按`Space`键执行选中操作
  radio.addEventListener("keydown", e => {
    if (e.keyCode === 32){
      e.target.click()
    }
  })
})
Copy after login
There are three points to note in this implementation:

1. Pass label passes the mouse click event to the associated input[type=radio], so you can safely hide the radio button and make use of the radio button's own characteristics. However, due to the limitations of the label control itself, for example, it is not a focusable element by default, so keyboard key events cannot be transferred to the radio button. Even if the tabindex feature is added, handwritten JS is required to implement it;

2. When tabindex is greater than or equal to When 0, it means that the element can get focus. When it is 0, it means that the order of focus is arranged according to the location of the element. When it is greater than 0, it means that the smaller the element, the focus will be obtained first;

3. Since the display of the radio button is inline-block, so the radio button will affect the line box height. When the elements in the custom radio button are inline-block, if the vertical-align setting is slightly careless, the line box where the internal element is located will be raised, causing the height of the line box where the custom radio button is located to become larger. . Therefore, here we adopt the method of setting the display of internal elements to block, which directly disables vertical-align and improves controllability.

Achieved through opacity:0

Above we associate the input[type=radio] of display:none with label to simplify the custom order using input[type=radio] The implementation of the selection box, but still requires handwriting JS to implement the behavioral characteristics of pressing the Space key to select. Is there another way that can save trouble? We just want users not to see the native radio button, so can we just set it to opacity:0? !

CSS part

.radio {
  /* 保证布局特性保持一致 */
  margin: 3px 3px 0px 5px;
  display: inline-block;
  box-sizing: border-box;

  width: 13px;
  height: 13px;
}
/* 自定义单选框的行为主要是基于原生单选框的,因此先将原生单选框透明,且沾满整个父元素 */
.radio input {
  opacity: 0;
  position: absolute;
  z-index: 1; /* 必须覆盖在.radio__appearance上才能响应鼠标事件 */
  width: 100%;
  height: 100%;
}
.radio__container-box{
  position: relative;
  width: 100%;
  height: 100%;
}
.radio__appearance{
  display: block; /* 设置为block则不受vertical-align影响,从而不会意外影响到.radio的linebox高度 */
  position: relative;
  box-shadow: 0 0 0 1px tomato; /* box-shadow不像border那样会影响盒子的框高 */
  border-radius: 50%;
  height: 90%;
  width: 90%;
  text-align: center;
}
.radio [type=radio] + .radio__appearance::before{
  content: "";
  display: block;
  border-radius: 50%;
  width: 85%;
  height: 85%;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  transition: background .3s;
}
.radio [type=radio]:checked + .radio__appearance::before{
  background: tomato;
}
.radio [type=radio][disabled] + .radio__appearance{
  opacity: .5;
}
.radio:focus-within .radio__appearance{
  outline-offset: 0px;
  outline: #999 auto 5px;
}
/* 通过鼠标单击获得焦点时,outline效果不生效 */
.radio.clicked .radio_appearance{
  outline: none 0;
}
Copy after login
HTML part

<!-- 未选中状态 -->
<span>
  <span>
    <input>
    <i></i>
  </span>
</span>

<br>

<!-- 选中状态 -->
<span>
  <span>
    <input>
    <i></i>
  </span>
</span>

<br>

<!-- disabled状态 -->
<span>
  <span>
    <input>
    <i></i>
  </span>
</span>
Copy after login
JavaScript part

var radios = document.querySelectorAll(".radio")
radios.forEach(radio => {
  // 模拟鼠标点击后:focus样式无效
  radio.addEventListener("mousedown", e => {
    var tar = e.currentTarget
    tar.classList.add("clicked")
    var fp = setInterval(function(){
      if (!tar.contains(document.activeElement){
        tar.classList.remove("clicked")
        clearInterval(fp)
      }
    }, 400)
  })
})
Copy after login
Summary

We can slightly modify the check box That’s it, and then it can be slightly encapsulated through VUE, React and other frameworks to provide a simpler API, which will be more convenient to use.

The above is the detailed content of How to change the color of radio button using css (code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template