checkbox点击事件修改样式

Kitty ·
更新时间:2024-09-20
· 868 次阅读

由于需要个性化checkbox的点击事件,不得以研究了一下点击事件。奈何这个项目组居然没有checkbox的样式,看着这原生的样式丑到爆,不得以研究了一下checkbox。(radio也是同理,区别是最好通过条件控制只能单选。)

这里先附上样式灵感来源地址
如果有需要变更图标的,可以在上述地址选取。

效果图:

tip:需要用到jquery,注意导入。
checkbox.js

$(function() { //activeCheckBox(); activeCheckBoxBySelector("", addSpan); }); /* 激活所有的的checkboxdiv*/ function activeCheckBox() { //初始化选中状态 $(".checkboxdiv").each(function() { var checked = $(this).find("input").prop("checked"); if (checked) { $(this).find(".checkboxstatus").addClass("checked"); } else { $(this).find(".checkboxstatus").removeClass("checked"); } }) //初始化按钮事件 $(".checkboxdiv").on("click", function() { var checked = $(this).find("input").prop("checked"); if (checked) { $(this).find("input").prop("checked", false) $(this).find(".checkboxstatus").removeClass("checked"); } else { $(this).find("input").prop("checked", true) $(this).find(".checkboxstatus").addClass("checked"); } }) } /* 只激活某块地区的checkbox,个性化方法,避免影响其他.*/ function activeCheckBoxBySelector(selector, callback) { var selector = selector + ' .checkboxdiv'; //初始化选中状态 $(selector).each(function() { var checked = $(this).find("input").prop("checked"); if (checked) { $(this).find(".checkboxstatus").addClass("checked"); } else { $(this).find(".checkboxstatus").removeClass("checked"); } }) //初始化按钮事件 $(selector).on("click", function() { var checked = $(this).find("input").prop("checked"); if (checked) { $(this).find("input").prop("checked", false) $(this).find(".checkboxstatus").removeClass("checked"); callback(this); } else { $(this).find("input").prop("checked", true) $(this).find(".checkboxstatus").addClass("checked"); callback(this); } }) } function addSpan(that) { var checked = $(that).find("input").prop("checked"); if (checked) { $(that).find("span").text("选中了"); } else { $(that).find("span").text("未选中"); } }

tip:这里提供了两种方法,如果没有其他事件用第一种;如果有自定义事件,用第二种即可。
checkbox.css

/* 用div包装 */ .checkboxdiv { display: inline-block; position: relative; margin-left: 28px; margin-bottom: 50px; } /* 隐藏原来的样式 */ .checkboxdiv input[type=checkbox] { visibility: hidden; } /* 定义边框样式 */ .checkboxdiv .label { display: block; width: 20px; height: 20px; line-height: 20px; cursor: pointer; position: absolute; border: 1px solid #ccc; top: 6px; left: 6px; } /* 定义选中样式(使用伪元素)*/ .checkboxdiv .checked div:before { display: block; content: "\2714"; text-align: center; font-size: 20px; color: red; }

新手上路,请多关照。


作者:最爱的夏威夷果



checkbox 事件

需要 登录 后方可回复, 如果你还没有账号请 注册新账号