HTML代碼:
<h4>開關</h4>
<label class="switch">
<input type="checkbox" name="switch" checked>
<span></span>
</label>
CSS代碼:
.switch {cursor: pointer;}
.switch span {
display: inline-block;
width: 36px; height: 20px;
border-radius: 10px;
background-color: #999;
position: relative;
/* 0.4秒切換背景色 */
transition: background-color .4s;
}
.switch span:before {
content: '';
width: 16px; height: 16px;
border-radius: 50%;
position: absolute;
left: 2px; top: 2px;
background-color: #fff;
/* 0.4秒切換左邊距離 */
transition: left .4s;
}
.switch input {display: none;}
/* 藉助input的checked屬性實現切換 */
.switch input:checked + span {
background-color: #2979ff;
/* 0.4秒切換背景色 */
transition: background-color .4s;
}
.switch input:checked + span:before {
left: 18px;
/* 0.4秒切換左邊距離 */
transition: left .4s;
}
效果圖: