需求
原生的checkbox的样式基本不能满足项目的要求。在项目上,常常不使用原生的checkbox,而做个假的,通过点击事件来判断是否选中。
但往往,这并不是一个好的办法。如何解决?可以通过伪类来自定义checkbox的样式。
原生checkbox样式:
自定义checkbox样式:
实现
demo:https://jsfiddle.net/ken0qvj6/1/
<div>
<input type="checkbox">
<span>同意条款</span>
</div>
给checkbox添加一个伪类,这部分会覆盖在原生的checkbox上,定义好未选中时的样式。选中时,将content替换为勾的字符,修改颜色和背景色自定义选中时的样式。
input[type=checkbox] {
position: relative;
width: 15px;
height: 15px;
margin-right: 5px;
cursor: pointer;
}
input[type=checkbox]:after {
display: inline-block;
content: "";
width: 15px;
height: 15px;
border-radius: 3px;
background: #fff;
border: 1px solid #ddd;
}
input[type=checkbox]:checked:after {
content: "✓";
font-size: 12px;
font-weight: bold;
color: #fff;
background-color: #7f7159;
text-align: center;
}