Jquery模拟多选框(checkbox)

时间:2022-01-30 20:00:26

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jquery模拟多选框(checkbox)</title>
<style>
body,div,input{margin:0;padding:0;}
body{margin-top:100px;font-size:12px;}
i,em{font-style:normal;} .grow-checked-list{text-align:center;}
.grow-checked-list .checkbox_item{position:relative;display:inline-block;margin-right:10px;height:16px;}
.checkbox_item input{position:absolute;top:-9999px;left:-9999px;}
.checkbox_item .check_label{display:inline-block;cursor:default;}
.checkbox_icon{display:block;float:left;margin-right:5px;width:16px;height:16px;background:url(img/checkbox_icon.png) 0 0;}
.check_label.on .checkbox_icon{background-position:-16px 0;}
.checkbox_text{float:left;height:16px;line-height:16px;}
</style>
</head>
<body>
<div class="grow-checked-list">
<span class="checkbox_item">
<input type="checkbox" />
<label class="check_label on">
<i class="checkbox_icon "></i>
<em class="checkbox_text">项目一</em>
</label>
</span>
<span class="checkbox_item">
<input type="checkbox" />
<label class="check_label">
<i class="checkbox_icon"></i>
<span class="checkbox_text">项目二</span>
</label>
</span>
<span class="checkbox_item">
<input type="checkbox" />
<label class="check_label">
<i class="checkbox_icon"></i>
<span class="checkbox_text">项目三</span>
</label>
</span>
</div>
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/checkbox.js" type="text/javascript"></script>
<script type="text/javascript">
$(".check_label").checkbox();
</script>
</body>
</html>
checkbox.js如下:
;(function($){
$.fn.extend({
checkbox : function(){
return this.each(function(){
var $this = $(this);
if($this.hasClass("on")){
$this.siblings("input").prop("checked","checked");
}else{
$this.siblings("input").removeAttr("checked");
}
$this.on("click",function(){
if($this.hasClass("on")){
$this.siblings("input").removeAttr("checked");
$this.removeClass("on");
}else{
$this.siblings("input").prop("checked","checked");
$this.addClass("on");
}
});
});
}
});
})(jQuery);