Css实现checkbox复选框亲身实践

278 阅读1分钟

企业微信20220325-221243@2x.png

html原生的复选框样式很难满足我们的日常的开发需求,正好最近的的需求是要实现一个复选框,但是不巧没有在小组的组件库中找到,只能自己去动手了,实现思路lable标签+input输入框

介绍lable标签

label 标签为 input 元素定义标签,如果用户点击 label 元素内的文本,则会切换到控件本身,label 标签的 for 属性应该等于相关元素的 id 元素,以便将它们捆绑起来

实现代码

<div class="mkt-checkbox">
    <div class='check-icon'>
      <input type="checkbox" name="check" id="check" v-model="ischecked" @change="handleChange">
      <label for="check" class="notice"></label>
    </div>
    <div class="check-des">不再提醒</div>
</div>

//css部分
.mkt-checkbox{
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  .check-icon{
    display: flex;
    align-items: center;
    input{
      display: none;
    }

    .notice{
      height: 20px;
      width: 20px;
      display: inline-block;
      background-image   : url('https://si.geilicdn.com/img-3e190000017db7df903b0a207569-unadjust_24_24.png');
      background-repeat  : no-repeat;
      background-size    : 20px 20px;
      
    }

    input:checked+.notice{
      height: 20px;
      width: 20px;
      display: inline-block;
      background-image: url('https://si.geilicdn.com/img-680e0000017db893cf290a22d4b2-unadjust_24_24.png');
      background-repeat  : no-repeat;
      background-size    : 20px 20px;
    }
  }

  .is_checked{
    background-image: url('https://si.geilicdn.com/img-680e0000017db893cf290a22d4b2-unadjust_24_24.png');
  }

  .check-des{
    margin-left: 2px;
  }
}

给input添加了一个v-model用于输入框的变化,功能虽然很小,但也是对基础知识的复习,如果总是去cv现成的组件,那么非常基础的东西也会忘掉,目前还在实习阶段的我需求要一点点积累,早日进阶!