在前端开发过程中,对于单选、多选按钮,遇到的问题大致有如下两个:
第一,对于类似于单选多选答题,更希望能够实现点击选项也能够使得按钮选中,这得如何实现呢?
第二,默认的单选、多选按钮颜值是真得很low啊,可否进行微整呢?
一、实现点击选项选中按钮选中
有两种方式:
1、将label标签把选框和文本一起包围
<label>
<input type="checkbox" value="1" name="checkboxDemo" />选项一
</label>
<label>
<input type="checkbox" value="2" name="checkboxDemo" />选项二
</label>
2、要使label的for 和选框的id名字对应
<input type="checkbox" id="name1" />
<label for="name1">选项2</label>
<input type="checkbox" id="name2" />
<label for="name2">选项2</label>
二、提升一下颜值
如何提升颜值呢?方法比较简单,利用上述点击选项即可使按钮选中,将默认的单选或者多选按钮隐藏,用图片替代。
第一种方式,直接上代码,利用了伪选择器
<head>
<style>
input{
display: none
}
label{
background: url(img/option.png) no-repeat left center;
line-height: 28px;
display: block; padding: 5px 0 5px 35px;
}
input[type=checkbox]:checked+label{
background: url(img/option_on.png) no-repeat;
}
</style>
</head>
<body>
<input type="checkbox" id="name1" />
<label for="name1">选项2</label>
<input type="checkbox" id="name2" />
<label for="name2">选项2</label>
</body>
第二种方式,则需要使用js
<head>
<script type="text/javascript">
$(function(){
$("input[type='checkbox']").click(function(){
if($(this).is(':checked')){
$(this).attr("checked","checked");
$(this).parent().removeClass("off").addClass("on");
}else{
$(this).removeAttr("checked");
$(this).parent().removeClass("on").addClass(" off");
}
});
});
</script>
<style>
label{
background: url(img/option.png) no-repeat left center;
line-height: 28px;
display: block; padding: 5px 0 5px 35px;
}
.off{
background: url(img/option.png) no-repeat left center;
}
.on{
background: url(img/option_on.png) no-repeat left center;
}
input{display: none}
</style>
</head>
<body>
<label>
<input type="checkbox" value="1" name="checkboxDemo" />选项一
</label>
<label>
<input type="checkbox" value="2" name="checkboxDemo" />选项二
</label>
</body>
上效果图: