input实现的单选或复选,默认样式是很丑的,UI设计通常会设计出各种花样,来满足视觉要求,在这里就说下怎么借助css来修改单选/复选框样式,首先我们来看下效果
1. 设置input 属性hidden对该input进行隐藏,或者通过display:none也可以
<input type="radio" name="type" id="adviceRadio1" value="1" checked hidden/>
2. 借助label for标签通过id绑定input ,这样在点击label时实际就是点击了input
<input type="radio" name="type" id="adviceRadio1" value="1" checked hidden/>
<label for="adviceRadio1" class="advice"></label>
3.定义label的样式,设置未选中状态的背景图
.advice{
height: 12px;
width: 12px;
display: inline-block;
background-image: url('http://bobostatic.oss-cn-hangzhou.aliyuncs.com/boboweex/lesson/web/icon/icon_radio_defaultChecked@3x.png');
background-repeat: no-repeat;
background-position: center;
vertical-align: middle;
margin-top: -4px;
}
4.使用相邻选择器设置选中状态label的样式
input[type="radio"]:checked + .advice{
background-image: url('http://bobostatic.oss-cn-hangzhou.aliyuncs.com/boboweex/lesson/web/icon/icon_radio_Checked@3x.png');
}
5. 完整代码
<label>
<input type="radio" name="type" id="adviceRadio1" value="1" checked hidden/>
<label for="adviceRadio1" class="advice"></label>
<span class="radio-name">问题</span>
</label>
<label>
<input type="radio" name="type" id="adviceRadio2" value="2" hidden/>
<label for="adviceRadio2" class="advice"></label>
<span class="radio-name">建议</span>
</label>
<style type="text/css">
.advice{
height: 12px;
width: 12px;
display: inline-block;
background-image: url('http://bobostatic.oss-cn-hangzhou.aliyuncs.com/boboweex/lesson/web/icon/icon_radio_defaultChecked@3x.png');
background-repeat: no-repeat;
background-position: center;
vertical-align: middle;
margin-top: -4px;
}
input[type="radio"]:checked + .advice{
background-image: url('http://bobostatic.oss-cn-hangzhou.aliyuncs.com/boboweex/lesson/web/icon/icon_radio_Checked@3x.png');
}
</style>
获取radio及checkbox选中的值
1.获取radio的值
使用jquery获取radio的值有3种方式:
$('input:radio:checked').val();
$("input[type='radio']:checked").val();
$("input[name='rd']:checked").val();
2.获取checkbox的值
var obj = document.getElementsByName("hobby");
var check_val = [];
for(k in obj){
if(obj[k].checked){
check_val.push(obj[k].value);
}
}
遇到的坑
一开始写的时候,我是使用伪元素的方式实现,先将input进行隐藏 ,然后设置input:after定义它的样式,代码如下:
//html
<input type="radio" name="sex" id="male" /><label for="male"> Male</label>
//css
input[type=radio]{
visibility: hidden;
}
input[type=radio]:checked::after{
background-image: url('./img/sprite.png');
background-repeat: no-repeat;
background-position: -59px -10px;
visibility: visible;
}
input[type=radio]::after{
content: ' ';
display: block;
height: 20px;
width: 20px;
background-image: url('./img/sprite.png');
background-repeat: no-repeat;
background-position: -24px -10px;
visibility: visible;
}
但是后来发现这种方式兼容性有问题,在firefox浏览器无法显示,经查资料是因为input不支持伪元素:after,:before 。
火狐浏览器无法插入内容DOM元素,伪元素都是在容器内进行渲染的。input无法容纳其他元素,因此它不支持伪元素。
input,img,iframe等元素都不能包含其他元素,所以不能通过伪元素插入内容。至于Chrome 中checkbox和radio可以插入应该就是bug了
input要配合其它容器元素(i,span)等实现预期效果