自定義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;
  width: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);
  width: 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: '';
  width: 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')
   }
 })

聲明:此博客為個人學習之用,如與其他作品雷同,純屬巧合,並請明示指出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM