//html部分
<body>
<p>这是一组radio按钮</p>
<section>
<input type="radio" name="radio" id="radio1">
<label for="radio1"></label> <br/>
<input type="radio" name="radio" id="radio2">
<label for="radio2"></label>
</section>
</body>
思路一
input[type=”radio”]是可以通过了label绑定的,即点击label同样可以选中radio
1.先隐藏radio本身,用label占位,并把label 的背景设置为初始状态。
2.通过input的checked状态,重新background-position的值
input[type="radio"] {
display: none;
}
label {
width: 16px;
height: 16px;
display: inline-block;
background-image: url("img.png");
background-repeat: no-repeat;
background-position: -24px -10px;
cursor: pointer;
}
input:checked + label{
background-position: -59px -10px;
}
ps:这个的实现不是很难,但是我觉得最难得是,不是太懂ps的情况下,也不用有一些测量像素工具的情况下,我一直在尝试position 的具体值,然后,总结了一点点tips:
1. 把label设置为和背景图片一样的大小
2. 用ps测定出第一个默认状态定位的具体距离,我用的ps的画框工具,太初级了吧,哈哈哈,比如,这里就测出离顶部10px,左边24px
3. 然后设定position(是负值哦),background-position: -24px -10px;
4. 再把label的大小变成一个图标的大小 width: 16px;height: 16px;
思路二
因为如果把label设定为了radio的位置,那么就失去了label和input可以绑定的这个特性
所以我的思考是,用label的before元素来实现radio的占位,然后label依旧是我们的那个label
input[type="radio"]{
display: none;
}
label:before{
content: '';
display: inline-block;
width: 16px;
height: 16px;
background-image: url("img.png");
background-repeat: no-repeat;
background-position: -24px -10px;
cursor: pointer;
}
input:checked + label:before{
background-position: -59px -10px;
}
ps:圆圈圈和文字咩有对齐,这个可以自行调整
checkbox实现,用的思路二
//html
<section class="checkbox">
<input type="checkbox" name="checkbox" id="check1" checked>
<label for="check1"> 苹果</label><br/>
<input type="checkbox" name="checkbox" id="check2">
<label for="check2"> 香蕉</label><br/>
<input type="checkbox" name="checkbox" id="check3">
<label for="check3"> 葡萄</label>
</section>
input[type="checkbox"]{
display: none;
}
.checkbox label:before{
content: '';
display: inline-block;
width: 16px;
height: 16px;
background-image: url("img.png");
background-repeat: no-repeat;
background-position: -24px -32px;
cursor: pointer;
}
.checkbox input:checked + label:before{
background-position: -59px -32px;
}
其实是和radio一样的实现方式,所以,可以用scss优化一下