实现自定义checkbox、radio样式

来源:互联网 发布:尚硅谷mysql视频下载 编辑:程序博客网 时间:2024/05/24 06:59

最近在学习百度前端学院的课程,其中有一节课是关于自定义chackbox、radio样式,而且刚刚好项目中也要使用到自定义checked、radio样式,于是就开始着手实现,我使用的是背景图定位的方法,实现的方法不局限于此,还有使用伪类和伪元素实现自定义样式的。下面看看背景图实现的自定义样式:

这是使用的背景图片:



这是html代码:

有一点需要注意的就是,label的for一定要与关联的input的id一样,这样才能够关联起来,不然就无法实现选取该选项

<div class="mainBlock"><div class="checkbox-bgimg"><!--背景图实现--><h5>喜欢吃的东西</h5><input type="checkbox" id="checkbox1"><label for="checkbox1"></label><i>水果</i>   <input type="checkbox" id="checkbox2"><label for="checkbox2"></label><i>蔬菜</i></div><div class="checkbox-vclass"><!--伪元素实现--><h5>喜欢的游戏</h5><input type="checkbox" id="checkbox3"><label for="checkbox3"></label><i>狼人杀</i>   <input type="checkbox" id="checkbox4"><label for="checkbox4"></label><i>你画我猜</i></div><div class="radio-bgimg"><!--背景图实现--><h5>性别</h5><input name="bgimg" type="radio" id="radio1"><label for="radio1"></label><i>男</i>   <input name="bgimg" type="radio" id="radio2"><label for="radio2"></label><i>女</i></div><div class="radio-vclass"><!--伪元素实现--><h5>职业</h5><input name="vclass" type="radio" id="radio3"><label for="radio3"></label><i>学生</i>   <input name="vclass" type="radio" id="radio4"><label for="radio4"></label><i>教师</i></div></div>


这是css代码:

注意:这里可以不将radio隐藏起来的,因为display:none以后无法使用tab键选取,可以将透明度设置为0来实现相同的效果,这里使用的是将radio隐藏起来的做法
.checkbox-bgimg input[type="checkbox"]{/*将原有的radio隐藏起来*/display: none;}.checkbox-bgimg label{/*设置初始的label背景*/cursor: pointer;background: url(../img/99322cf8c3283e42.png);background-position: -25px -32px;display: inline-table;height: 15px;width: 15px;}.checkbox-bgimg input[type="checkbox"]:checked + label{/*相邻选择符选择被选取的radio相邻的label标签,改变背景*/background-position: -60px -32px;}

这是实现的最终效果:




1 0