18-7-全选

时间:2019-09-07
本文章向大家介绍18-7-全选,主要包括18-7-全选使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            font-family: "Microsoft YaHei", serif;
        }

        body, dl, dd, p, h1, h2, h3, h4, h5, h6 {
            margin: 0;
        }

        ol, ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        img {
            border: none
        }
        #wrap{
            cursor: pointer;
        }
    </style>
</head>
<body>
<div id="wrap">
    <div>
        <input type="checkbox" id="box1"><label for="box1">11</label>
        <input type="checkbox" id="box2"><label for="box2">22</label>
        <input type="checkbox" id="box3"><label for="box3">33</label>
        <input type="checkbox" id="box4"><label for="box4">44</label>
        <input type="checkbox" id="box5"><label for="box5">55</label>
        <input type="checkbox" id="box6"><label for="box6">66</label>
    </div>
    <input type="checkbox" id="box7"><label for="box7">全选</label>
</div>
<script>
// 在原生表单中元素input的里边,checked和disabled在js里边是以布尔值的形式体现的
    let aInp = document.querySelectorAll("#wrap div input");
    let oBtn = document.getElementById("box7");
    let len = aInp.length;
    let num = 0;
    // console.log(aInp[0].disabled); false
    // console.log(aInp[0].checked); false 选中就是true
    // aInp[3].checked = "aaa"; 这样也是可以被选中的,只要后边是个真值就会被翻译为true赋予给他
    
    
    oBtn.onchange = function () {
        if (this.checked) {
            for (let i=0;i<len;i++) {
                aInp[i].checked = true;
            }
        }else{
            for (let i=0;i<len;i++) {
                aInp[i].checked = false;
            }
        }
    };
    for (let i=0;i<len;i++) {
        aInp[i].onchange = function () {
            if (this.checked){
                num++;
            } else{
                num--;
            }
            oBtn.checked = num===len;
        }
    }
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/zhangyu666/p/11479992.html