自定义checkbox样式,并解决点击事件触发两次问题

技术
html、css、jquery(3.5.0)

1、需求
自定义checkbox样式,解决点击事件触发两次问题

2、实现效果

3、重点代码
<label for='f'></label>

4、完整代码
html

<div class='list-box'>
    <div class="input-box">
      <input type="checkbox" value="f" name="f" id="f" style="display: none;">
      <!-- 不要这样写,会出现点击一次,触发2次的问题
      <label for='f'></label> -->
      <label></label>
      <span class="status">Breakfast</span>
    </div>
  </div>

css

.input-box {
  cursor:pointer;
  110px;
}
label {
  background-color: #ffffff;
  border: 1px solid #CDCDCD;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05), inset 0px -15px 10px -12px rgba(0, 0, 0, 0.05);
   20px;
  height: 20px;
  border-radius: 3px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 8px;
  cursor: pointer;
}
.checkbox{
  border: 1px solid #FF9D0D !important;
  background: #FF9D0D !important;
}
.checkbox:after{
  position: absolute;
  content: '';
   10px;
  height: 4px;
  border: 2px solid #fff;
  border-top-color: transparent;
  border-right-color: transparent;
  left: 50%;
  top: 50%;
  margin-left: -6px;
  margin-top: -6px;
  transform: rotate(-45deg);
}

js

 $(".list-box .input-box").on("click", function () {
   console.log(11111)
   var checked = $(this).find('input')[0].checked = !$(this).find('input')[0].checked;
   if(checked){
     $(this).find('label').addClass('checkbox')
   }else{
     $(this).find('label').removeClass('checkbox')
   }
 })

声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,并请明示指出

原文地址:https://www.cnblogs.com/liliy/p/14747780.html