CheckBox樣式修改的兩種實現方法


CheckBox樣式修改的兩種實現方法

需求

在實際的項目中我們經常會用到checkbox這類表單標簽,於是我們就面臨修改初始樣式的問題;這里總結兩種修改的方法:

  1. 利用label對checkbox 進行包裝
<div class="label">
<label role="checkbox">
    <span class="outer-checkbox">
        <input type="checkbox">
        <span class="inner-checkbox"></span>
    </span>
</label>
</div>
.outer-checkbox{
    white-space: nowrap;
    cursor: pointer;
    outline: none;
    display: inline-block;
    line-height: 1;
    position: relative;
    vertical-align: middle;
}
.label input[type=checkbox]{
    outline: none;
    opacity: 0;
    outline: none;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 0;
}
.label input[type=checkbox]:checked + .inner-checkbox{
    border-color: #409eff;
    background: #409eff;
}
.label input[type=checkbox]:checked + .inner-checkbox:after{
    transform: translate(-50%,-50%) scale(1);
}
.label .inner-checkbox{
    display: inline-block;
    border: 1px solid #dcdfe6;
    border-radius: 100%;
    width: 14px;
    height: 14px;
    background-color: #fff;
    position: relative;
    cursor: pointer;
    box-sizing: border-box;
    outline: none;
}
.label .inner-checkbox:after{
    display: inline-block;
    width: 4px;
    height: 4px;
    border-radius: 100%;
    background-color: #fff;
    content: "";
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%) scale(0);
    transition: transform .15s ease-in;
}
  1. 利用appearance 對checkbox所有樣式進行初始化
<div class="appearance">
    <input type="checkbox">
</div>
.appearance{
    width: 14px;
    height: 14px;
}
.appearance input[type=checkbox]{
    position: relative;
    display: inline-block;
    appearance: none;
    -webkit-appearance: none;
    width: 14px;
    height: 14px;
    outline: none;
    border: 1px solid #dcdfe6;
    background-color: #fff;
    border-radius: 100%;
    margin:0;
}
.appearance input[type=checkbox]:checked{
    border-color: #409eff;
    background: #409eff;
}
.appearance input[type=checkbox]:checked::after{
    transform: translate(-50%,-50%) scale(1);
}
.appearance input[type=checkbox]::after{
    display: inline-block;
    width: 4px;
    height: 4px;
    border-radius: 100%;
    background-color: #fff;
    content: "";
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%) scale(0);
    transition: transform .15s ease-in;
}

兼容性:IE不支持這個屬性;caniuse - appearance


免責聲明!

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



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