radio和checkbox由于不同的浏览器显示的样式不一致,因此我们需要自定义radio(单选框)和checkbox(多选框)的样式。基本原理就是贱radio和checkbox的自定义样式设置成图片背景,然后通过js或者jQuery给包裹radio和checkbox的label根据点击效果添加和删除类别,从而达到自定义radio和checkbox的假象。
下面直接上代码:
HTML代码
需要如下的HTML代码
Checkbox1
Checkbox2
Radio1
Radio2
Radio3
JavaScript代码
上面的代码是控制css样式的js代码,采用的是jQuery,所以一定要先引入jQuery文件。
CSS代码
最后的CSS代码,如下所示:
* { margin: 0; padding: 0; }
body {
font: 14px/18px 'HelveticaNeue-Light', 'Helvetica Neue', Arial, Helvetica, sans-serif;
color: #fff;
background: #333;
}
a:hover,
a:active {
outline: none;
}
/*form style*/
form {
width: 300px;
padding: 18px 20px 0;
margin:20px auto;
background-color: #0064cd;
background-image: -khtml-gradient(linear, left top, left bottom, from(#049cdb), to(#0064cd));
background-image: -moz-linear-gradient(#049cdb, #0064cd);
background-image: -ms-linear-gradient(#049cdb, #0064cd);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #049cdb), color-stop(100%, #0064cd));
background-image: -webkit-linear-gradient(#049cdb, #0064cd);
background-image: -o-linear-gradient(#049cdb, #0064cd);
background-image: linear-gradient(#049cdb, #0064cd);
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 5px 12px rgba(0,0,0,.4);
-moz-box-shadow: 0 5px 12px rgba(0,0,0,.4);
-khtml-box-shadow: 0 5px 12px rgba(0,0,0,.4);
box-shadow: 0 5px 12px rgba(0,0,0,.4);
}
fieldset {
border: 0;
padding-bottom: 9px;
}
label {
display: block;
cursor: pointer;
line-height: 20px;
padding-bottom: 9px;
text-shadow: 0 -1px 0 rgba(0,0,0,.2);
}
.checkboxes {
border-bottom: 1px solid #0064cd;
}
.radios {
padding-top: 18px;
border-top: 1px solid #049CDB;
}
.label_check input,
.label_radio input {
margin-right: 5px;
}
.has-js .label_check,
.has-js .label_radio {
padding-left: 34px;
}
.has-js .label_radio,
.has-js .label_check{
background: url(/sites/default/files/checkbox-radio-bg.png) no-repeat;
}
.has-js .label_radio {
background-position: 0 0;
}
.has-js .label_check {
background-position: 0 -100px
}
.has-js label.c_on {
background-position: 0 -150px;
}
.has-js label.r_on {
background-position: 0 -50px;
}
.has-js .label_check input,
.has-js .label_radio input { position: absolute; left: -9999px; }
效果图
最终生成的效果图,如下所示:
总结
以上就是使用纯CSS自定义radio(单选框)和checkbox(多选框)的样式的全部代码,代码可以直接拷贝运行,赶紧去试一下吧。
如果觉得《html给radio添加图片 使用纯CSS自定义radio(单选框)和checkbox(多选框)的样式》对你有帮助,请点赞、收藏,并留下你的观点哦!