JavaScript---全选、取消选择、反选

功能:全选、取消选中、反选

全选【inputs[i].checked = true;】

取消选中【inputs[i].checked = false;】

反选【 inputs[i].checked = !inputs[i].checked;】

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
        }

        #panel{
            width: 400px;
            box-shadow: 0 0 10px #000;
            margin: 100px auto;
            padding: 20px;
        }

        .panel-header{
            text-align: center;
            margin-bottom: 10px;
        }

        .panel-footer{
            text-align: center;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div id="panel">
        <section class="panel-header">
            <h2>节目单</h2>
            <hr>
        </section>
        <section class="panel-content">
            <input type="checkbox">1.爵士舞<br>
            <input type="checkbox">2.小品<br>
            <input type="checkbox">3.歌舞串烧<br>
            <input type="checkbox">4.诗词朗诵<br>
            <input type="checkbox">5.独唱<br>
            <input type="checkbox">6.大合唱<br>
            <input type="checkbox">7.芭蕾舞<br>
            <input type="checkbox">8.肚皮舞<br>
        </section>
        <section class="panel-footer">
            <hr>
            <button id="allSelect">全选</button>
            <button id="cancelSelect">取消选中</button>
            <button id="reverseSelect">反选</button>
        </section>
    </div>
    <script>
    window.onload = function() {
        // 1. 获取所有的复选框
        var inputs = document.querySelectorAll('input');

        // 2. 全选
        $("allSelect").onclick = function() {
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].checked = true;
            }
        };

        // 3. 取消选中
        $("cancelSelect").onclick = function() {
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].checked = false;
            }
        };

        // 4. 反选
        $("reverseSelect").onclick = function() {
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].checked = !inputs[i].checked;
            }
        };

        function $(id) {
            return typeof id === "string" ? document.getElementById(id) : null;
        }
    }
    </script>
</body>

</html>
发布了147 篇原创文章 · 获赞 33 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/maidu_xbd/article/details/101386025