1 checkbox 一般常用的有两种状态 一种是checked=true (选中状态) ,一种是checked=false(未选中状态);

 

 2 checkbox其实还有第三种状态 indeterminate=true(会在复选框里边显示一条横岗),如下

 

注意:indeterminate在html中无法设置 只能在jquire中才能进行设置

 

下边是实现一个总复选框有几个子复选框1 子复选框选中全部的时候总复选框选中;2 子复选框全部未选中的时候,总复选框未选中;3 部分子选项框选中,总选项框显示第三种状态的功能的代码,仅供没有思路的朋友们参考

HTML代码:

<div class="choice-item-all">
  <input type="checkbox" id="all-choice-left" name="all_choice_left">
  <label for="all-choice-left" style="margin-top: 4px">总复选框</label>
</div>
<div class="choice-item">
  input type="checkbox" value="0" id="choice-one" name="choice_left">
  <label for="choice-one">选项1</label>
</div>
<div class="choice-item">
  <input type="checkbox" value="1" id="choice-two" name="choice_left">
  <label for="choice-two">选项2</label>
</div>
<div class="choice-item">
  <input type="checkbox" value="2" id="choice-three" name="choice_left">
  <label for="choice-three">选项3</label>
</div>
<div class="choice-item">
  <input type="checkbox" value="3" id="choice-four" name="choice_left">
  <label for="choice-four">选项4</label>
</div>

 

js代码:

 

    let leftCheck = $('input[name="choice_left"]'); //获取所有子级复选框
    let leftCheckAll = document.getElementById('all-choice-left'); //获取总复选框。
   //对总复选框值进行动态监听,实现全选和全不选的功能
    1)$('#all-choice-left').change(function () {
        //如果总复选框选择了则获取所有子级复选框然后遍历后将每个子选项的状态改为选中状态
        if (leftCheckAll.checked === true) {
            for (let i = 0; i < leftCheck.length; i++) {
                leftCheck[i].checked = true;
            }
            //如果总复选项框没有选择的时候获取子级复选框然后遍历后将每个子选项的状态改为未选中状态
        } else if (leftCheckAll.checked === false) {
            
            for (let i = 0; i < leftCheck.length; i++) {
                leftCheck[i].checked = false;
            }
        }
    })

   //要是看不懂上边的没关系,可以直接复制以下代码
   //点击总复选框的时候判断总复选框是否选中 然后改变所有子级复选框的状态
    2)$('#all-choice-left').click(function () {
        if($(this).prop('checked')){
                $('input[name="choice_left"]').prop('checked',true)
            }else {
                $('input[name="choice_left"]').prop('checked',false)
            }   
    })

//对所有子级进行监听,然后对总复选项框进行赋值
    $("input[name='choice_left']").change(function () {
        //获取所有选中的子级复选框
        let cxBoxChecked = $('input[name="choice_left"]:checked');
        //判断选中的子级复选框数量大于1个并且小于所有子级数量的时候
        if (cxBoxChecked.length > 0 && cxBoxChecked.length < leftCheck.length) {
            leftCheckAll.indeterminate = true;
        } else {
            leftCheckAll.indeterminate = false;
        }
        //判断选中子级复选框数量和子级复选框数量相同,总复选项框选中
        if (cxBoxChecked.length === leftCheck.length) {
            leftCheckAll.checked = true
        }
         //判断所有子级复选框都没有选中的情况时,总复选框没有选中
        if (cxBoxChecked.length === 0) {
            leftCheckAll.checked = false
        }
    })

 

效果: