基于纯js对单选框的美化,不仅可以设置想设置的颜色,也可以在同一页面复用多个。还会对代码进行详细的解析,对刚入门的你有一定的帮助哦~
css:
.radio{display:inline-block;
width:20px;height:20px;
border-radius:50%;
border:1px solid #666;
margin-right:5px;
margin-bottom:20px;
vertical-align:top;
text-align:center;
cursor:pointer;
user-select:none;
}
//用伪类的方式在类名radio的后面添加一个标签,并且内容为:•;注意:内容仅为文本模式,不能为图片等内容
content:"•";
font-size:30px;
line-height:20px;
}
html
<div class="radio-group">
<label><input type="radio" name="sex" value="男" checked> 男</label>
<label><input type="radio" name="sex" value="女"> 女</label>
</div>
<div class="radio-group">
<input type="radio" name="xueli" value="本科"> 本科
<input type="radio" name="xueli" value="大专"> 大专
</div>
<div class="radio-group">
<input type="radio" name="xueli2" value="本科"> 本科
<input type="radio" name="xueli2" value="大专" checked> 大专
</div>
js:
//单选框插件
var radioGroup=document.querySelectorAll('.radio-group'); //获取浏览器中所有的类名为radio-group的文件。
querySelectorAll:是js中一种方法,查找多个的意思
radioGroup.forEach(function(group){
//forEach()方法用于调用数组的每个元素,并将元素传递给回调函数。
它有三个参数:function(currentValue, index, arr);第一个参数表示的是你当前所触发事件的元素,这个是必选的;第二个参数是当前元素的索引值,这个是可选的;第三个参数是指当前元素所属的数组对象,这个是可选的。
var radios=group.querySelectorAll('input[type="radio"]');
//获取到浏览器中所有的类型为radio的文件。
radios.forEach(function(radio){
//隐藏原生态控件
radio.style.display='none';
//创建一个span元素;
var span=document.createElement('span');
span.className='radio'+(radio.checked?' active':'');radio.parentNode.insertBefore(span,radio);
span.οnclick=function(){
//清除所有span的active
group.querySelectorAll('span.radio').forEach(function(item){
item.className='radio';
})
this.className='radio active';
radio.checked=true;
}
})
})
做的不好的地方也欢迎广大前端工程师提意见哦~