zoukankan      html  css  js  c++  java
  • 原生js实现复选框

    简单排版

    <style>
    
    .box {
    display: flex;
    align-items: center;
    }
    
    #allSelect,
    p {
     20px;
    height: 20px;
    margin-top: 5px;
    position: relative;
    }
    
    li {
    list-style: none;
    display: flex;
    align-items: center;
    }
    
    span {
     20px;
    height: 20px;
    border: 1px solid #000;
    display: inline-block;
    }
    
    .selectk {
    position: absolute;
     100%;
    height: 100%;
    background: #000;
    top: 0;
    left: 0;
    }
    .selectk::after {
    content: "✔";
    display: inline-block;
    text-align: center;
    line-height: 20px;
    color: #fff;
    }
    </style>
    </head>
    <body>
    <div class="box">全选:<div id="allSelect"><span></span></div>
    </div>
    <ol>
    <li><p><span></span></p></li>
    <li><p><span></span></p></li>
    <li><p><span></span></p></li>
    <li><p><span></span></p></li>
    <li><p><span></span></p></li>
    <li><p><span></span></p></li>
    <li><p><span></span></p></li>
    </ol>
    </body>

    功能实现

      <script>
        var arr = [];
        //获取所有的复选按钮
        var ospan = document.querySelectorAll("p>span"); 
         //获取页面的全选按钮
        var checkBtn =  document.querySelector("#allSelect");
        //复选按钮点击时
        [...ospan].forEach(function(item,index){
          item.addEventListener("click",function(){
            this.classList.toggle("selectk");
              if(this.classList.contains("selectk")){
                  arr.push(index);  
              }else{
                  arr.splice(index,1);
              }
              if(arr.length === [...ospan].length){
                checkBtn.classList.add("selectk")
              }else{
                checkBtn.classList.remove("selectk")
              }
          })
        })
        // 点击全选按钮
        checkBtn.addEventListener("click",function(){
          this.classList.toggle("selectk");
          if(this.classList.contains("selectk")){
            [...ospan].forEach(function(item,index){
              item.classList.add("selectk")
            })
          }else{
            [...ospan].forEach(function(item,index){
              item.classList.remove("selectk")
            })
          } 
        })
      </script>

    效果展示

    本人小白,欢迎指正!!

  • 相关阅读:
    Grodno 2015 (Urozero May 2015 Day 5) D Triangles
    Flea Circus(Project Euler 213)
    Prime triplets (Project Euler 196)
    ACM 博弈(难)题练习 (第二弹)
    Crosses Puzzles zoj 4018 (zju校赛)
    Petrozavodsk Summer-2015. Ivan Smirnov Contest 1 B Bloom
    ACM 博弈(难)题练习 (第一弹)
    2017 ACM区域赛(南宁站) 参赛流水账
    2017 CCPC 杭州 流水账
    2017 ACM区域赛(西安) 参赛流水账
  • 原文地址:https://www.cnblogs.com/PengZhao-Mr/p/10969623.html
Copyright © 2011-2022 走看看