自定义单选,多选按钮

html:
<div data-toggle="buttons" style="margin-bottom:30px;">
<a style="position: relative" class="mybtn">
<span>男</span>
<input type="radio" name="sex1" style="position: absolute">
</a>
<a style="position: relative" class="mybtn">
<span>女</span>
<input type="radio" name="sex1" style="position: absolute">
</a>
</div>

<div data-toggle="buttons">
<a style="position: relative" class="mybtn">
<span>喜欢打球</span>
<input type="checkbox" name="sex2" style="position: absolute">
</a>
<a style="position: relative" class="mybtn">
<span>喜欢看书</span>
<input type="checkbox" name="sex2" style="position: absolute">
</a>
<a style="position: relative" class="mybtn">
<span>喜欢画画</span>
<input type="checkbox" name="sex2" style="position: absolute">
</a>
<a style="position: relative" class="mybtn">
<span>喜欢摄影</span>
<input type="checkbox" name="sex2" style="position: absolute">
</a>
</div>
css:
.mybtn{
background: #ebebeb;
padding: 5px 10px;
color: #333;
border-radius: 6px;
border:1px solid #ddd;
margin:0px 5px;
cursor: pointer;
}
.mybtn input{
visibility: hidden;
position: absolute;
}
.mybtn.active{
background: #59a2ff;
color: #fff;
}
jquery:
+(function($){
var Button = function(element){
this.$element = element;
}
Button.prototype.toggle = function(){
$parents = this.$element.parents('[data-toggle="buttons"]');
if($parents.find('[type="radio"]').length>0){
//单选
$parents.find(".active").removeClass("active");
this.$element.addClass("active");
this.radioChecked();
}else {
//多选
this.$element.toggleClass("active");
this.checkboxChecked();
}
}
Button.prototype.radioChecked = function(){
var $radio = this.$element.find('[type="radio"]');
$radio.prop("checked",true);
}
Button.prototype.checkboxChecked = function(){
var $checkbox = this.$element.find('[type="checkbox"]');
if(this.$element.hasClass("active")){
$checkbox.prop("checked",false);
}else{
$checkbox.prop("checked",true);
}
}
$(function () {
$(document).on("click",'[data-toggle="buttons"]',function (e) {
var $btn = $(e.target);
//若点击到的是内部的span,委托,参考jQuery API:http://jquery.cuishifeng.cn/closest.html
if (!$btn.hasClass('mybtn')) $btn = $btn.closest('.mybtn')
new Button($btn).toggle();
})
})
})(jQuery);

猜你喜欢

转载自www.cnblogs.com/yuyedaocao/p/9856376.html