多选框在工作中经常会用到,但浏览器默认的样式往往不能达到要求,而且不同浏览器的默认样式不同。可以通过自定义样式来解决这一问题。
实现思路
将原有的checkbox透明度设置为0,用css3的伪类选择符:checked选中checkbox选中时的状态,然后将样式设置到自定义元素上,具体实现如下:
html
<input type="checkbox">
<span class="c-checkbox">
<input type="checkbox" class="c-checkbox-input">
<span class="c-checkbox-inner"></span>
</span>
css
.c-checkbox {
display: inline-block;
vertical-align: middle;
white-space: nowrap;
cursor: pointer;
line-height: 1;
position: relative;
}
input:checked + .c-checkbox-inner{
background: #008ccf;
}
input:checked + .c-checkbox-inner:after{
content:"";display:table;
width:4px;
height:8px;
position:absolute;
top:1px;
left:4px;
border:2px solid #fff;
border-top:0;
border-left:0;
-webkit-transform:rotate(45deg) scale(1);
transform:rotate(45deg) scale(1);
transition:all .2s ease-in-out
}
.c-checkbox-inner {
display: inline-block;
width: 14px;
height: 14px;
position: relative;
top: 0;
left: 0;
border: 1px solid #dddee1;
border-radius: 2px;
background-color: #fff;
transition: border-color .2s ease-in-out,background-color .2s ease-in-out,box-shadow .2s ease-in-out;
}
.c-checkbox-input {
width: 100%;
height: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 1;
cursor: pointer;
opacity: 0;
}
最终实现效果如下:
此方法的优点是,不用id属性,通过class属性内对多个元素同时作用,缺点是,用到一些css3,低版本浏览器不支持。