一、基本用法
inputcheckbox是HTML5提供的一个多选框元素,可以通过设置type属性为checkbox来创建。
<input type="checkbox" name="fruit" value="apple"> 苹果
<input type="checkbox" name="fruit" value="banana"> 香蕉
<input type="checkbox" name="fruit" value="orange"> 橙子
上述代码中,name属性设置了多个多选框的分组属性,value属性设置了每个多选框对应的值。
当需要默认选中某些多选框时,可以通过在checked属性设置为true来实现:
<input type="checkbox" name="fruit" value="apple" checked> 苹果
<input type="checkbox" name="fruit" value="banana"> 香蕉
<input type="checkbox" name="fruit" value="orange" checked> 橙子
二、全选与取消全选
经常情况下,我们需要在一组多选框中设置全选和取消全选的功能。这可以通过两个操作分别来实现:
<input type="checkbox" id="check-all"> 全选
<input type="checkbox" name="fruit" value="apple" class="check-one"> 苹果
<input type="checkbox" name="fruit" value="banana" class="check-one"> 香蕉
<input type="checkbox" name="fruit" value="orange" class="check-one"> 橙子
$(function(){ $("#check-all").click(function(){ $(".check-one").prop("checked", $(this).prop("checked")); }); $(".check-one").click(function(){ if($(this).prop("checked") == false){ $("#check-all").prop("checked", false); } else if($(".check-one:checked").length == $(".check-one").length){ $("#check-all").prop("checked", true); } }); });
通过上述JavaScript代码,当用户点击全选的多选框时,通过遍历页面中class为check-one的所有多选框,来设置它们的checked属性。当其中任意一个多选框被取消选中时,取消全选的多选框也相应的取消选中;当全部多选框被选中时,则选择全选的多选框也相应的选中。
三、多选框的样式及功能拓展
在实际应用中,经常需要将多选框的样式进行美化,或者为其添加更加丰富的功能。
1. 美化多选框的样式
通过CSS样式来美化多选框的外观。
.checkbox { position: relative; display: inline-block; padding-left: 25px; margin-right: 10px; font-size: 14px; cursor: pointer; } .checkbox input[type="checkbox"] { position: absolute; opacity: 0; cursor: pointer; } .checkmark { position: absolute; top: 0; left: 0; height: 20px; width: 20px; border: 1px solid #ccc; border-radius: 3px; } .checkbox:hover input ~ .checkmark { background-color: #ccc; } .checkbox input:checked ~ .checkmark { background-color: #2196F3; border-color: #2196F3; } .checkmark:after { content: ""; position: absolute; display: none; } .checkbox input:checked ~ .checkmark:after { display: block; } .checkbox .checkmark:after { left: 7px; top: 3px; width: 5px; height: 10px; border: solid white; border-width: 0 2px 2px 0; transform: rotate(45deg); }
上述样式设置了多选框的容器样式以及多选框的样式,当鼠标移动到多选框上时,其样式会发生变化。当多选框选中时,其样式也会发生变化。
2. 选择框级联效果
选择框级联效果,即在第一个多选框选定后对之后的多选框进行筛选,换言之,第二个多选框将根据第一个多选框中选中的值来显示与隐藏。
$(function(){ $("[name='type1']").click(function(){ var type1 = $(this).val(); $(".type2").addClass("hide"); $(".type2-" + type1).removeClass("hide"); }); });
当用户点击选择类别1中的某个多选框时,通过遍历class为type2的所有多选框,来设置其display属性的不同值来实现级联效果。
原创文章,作者:DEOUA,如若转载,请注明出处:https://www.506064.com/n/370349.html