純css實現checkbox開關切換按鈕


我們都知道 checkbox 標簽默認樣式 實在是太low了,故對CheckBox美化很有必要。

現提供兩種方式對其進行美化。

方法一

<div class="switch-wrap active">
    <span></span>
</div>
.switch-wrap{
  position: relative;
  display: inline-block;
  width: 52px;
  height: 32px;
  border: 1px solid #DFDFDF;
  outline: none;
  border-radius: 16px;
  box-sizing: border-box;
  background: #FFFFFF;
  cursor: pointer;
  transition: border-color .3s,background-color .3s;
  vertical-align: middle;
}
.switch-wrap span{
  position: absolute;
  top: 0;
  left: 0;
  transition: transform 0.3s;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.4);
  background-color: #fff;
}
.switch-wrap.active{
  border-color: #33DB70;
  background-color: #33DB70;
}
.switch-wrap.active span{
  transform: translateX(20px);
}

控制切換通過添加類名 active 來控制 

相關jQuery代碼為

$(".switch-wrap").click(function(){
    if($(this).hasClass("active")){
       $(this).removeClass("active");
    }else{
      $(this).addClass("active");
    }
})

 

預覽地址:https://zuobaiquan.github.io/css3/純css實現checkbox開關切換按鈕/01/index.html

源碼地址 https://github.com/zuobaiquan/css3/tree/master/純css實現checkbox開關切換按鈕/01

 

方法二

當點擊 label ,光標會根據for 屬性指向checkbox中的 id 

<div class='switch-wrap'>
      <input type='checkbox' id= 'switch'>
      <label for='switch'></label>
</div>
.switch-wrap input[type=checkbox]{
  height: 0px;
  width: 0px;
  visibility: hidden;
  margin:0;
  padding:0;
}
.switch-wrap label{
  display: inline-block;
  width: 52px;
  height: 32px;
  border: 1px solid #DFDFDF;
  outline: none;
  border-radius: 16px;
  box-sizing: border-box;
  background: #FFFFFF;
  cursor: pointer;
  transition: border-color .3s,background-color .3s;
  vertical-align: middle;
  position: relative;
}
.switch-wrap label::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  transition: transform 0.3s;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.4);
  background-color: #fff;
}
.switch-wrap input:checked + label {
  background: #33DB70;
}
.switch-wrap input:checked + label:before {
  transform: translateX(20px);
}

這里純粹的是css控制開關切換。無相關的js邏輯代碼

預覽地址:https://zuobaiquan.github.io/css3/純css實現checkbox開關切換按鈕/02/index.html

源碼地址 https://github.com/zuobaiquan/css3/tree/master/純css實現checkbox開關切換按鈕/02

 

總結

方法一利用js控制開關邏輯。通過類名active來實現開關切換。方法二利用checkbox點擊來控制開關切換。通過label指向 checkbox的id來控制。其缺點:id具有唯一性;與后端邏輯交互較難控制開關狀態。故方法一可取。


免責聲明!

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



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