基于 Bootstrap 和 jQuery 的 checkbox 的应用
checkbox的单选多选组件
在网上找了插件自己改了一下,比原生的好看些,也可以自己修改
- HTML
1 单选<lable> <i class="input_style checkbox_bg"> <input type="checkbox" name="addcart" value="1"> </i> </lable>
2 多选
<lable>
<i class="input_style checkbox_bg" style="margin-left: 30px;">
<input type="checkbox" id="checkall" name="checkall">
</i> 全选
</lable>
- CSS
.input_style{
background: url(../../images/green.png) no-repeat;
width: 20px;
height: 20px;
display: inline-block;
}
.radio_bg_check{
background-position: -166px 0 ;
}
.checkbox_bg_check{
background-position: -48px 0;
}
- JS(基于jQuery的)
(function($) {
$.extend({ //进行方法的扩展
inputStyle: function() {
function check(el, cl) { //el 为传入的对象,cl为进行变化的claa样式,可以自定义,也可以直接用我的
$(el).each(function() {
$(this).parent('i').removeClass(cl);
var checked = $(this).prop('checked');
if (checked) {
$(this).parent('i').addClass(cl);
}
})
}
function checkall(el, cl) { //对于全选的操作
$(el).each(function() {
$(this).prop("checked", true); //将checked属性改为true
$(this).parent('i').addClass(cl); //将选中样式加上
})
}
function checkadeletall(el, cl) { //对于全不选的操作
$(el).each(function() {
$(this).prop("checked", false);
$(this).parent('i').removeClass(cl);
})
}
// radio的利用, 此篇主要事针对于checkbox的应用, 若想用radio的可以自行修改
// $('input[type="radio"]').on('click', function() {
// check('input[type="radio"]', 'radio_bg_check');
// })
$('input[name="addcart"]').on('click', function() { //当点击单选框
check('input[name="addcart"]', 'checkbox_bg_check');//传入对象为input[name="addcart"],样式为checkbox_bg_check
console.log("进入点击")
if ($(this).is(':checked')) { //应甲方要求,当本来点击全选按钮,全部选中时,再点击单选框使其不为全选状态时,全选按钮自动的变为不选样式
console.log("checkall若选中,则还是选中,若没有,无变化")
return;
} else {
console.log("checkall不选中!");
$('input[name="checkall"]').attr("checked", false); //将属性改为checked ,false
$('input[name="checkall"]').parent('i').removeClass('checkbox_bg_check'); //将样式去除
}
})
$('input[name="checkall"]').on('click', function() {
check('input[name="checkall"]', 'checkbox_bg_check'); //先让他自身选中
if ($(this).is(':checked')) {
$('input[name="addcart"]').each(function() {
checkall('input[name="addcart"]', 'checkbox_bg_check'); //当全选时,触发全选函数
});
} else {
$('input[name="addcart"]').each(function() {
checkadeletall('input[name="addcart"]', 'checkbox_bg_check'); //当不为全选时,触发不全选按钮
});
}
})
}
})
})(jQuery)
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: