HTML
<input id="customSwitch" type="checkbox" />
<label for="customSwitch" class="switch"></label>
CSS
/* 定義全局變量 */
:root {
--base_color: rgba(0, 0, 0, 0.25);
--act_color: #5dcb61;
}
/* 隱藏input輸入框 */
#customSwitch {
position: absolute;
left: -9999px;
}
/* 設置自定義顏色 */
.switch {
position: relative;
display: inline-block;
width: 40px;
height: 20px;
background-color: var(--base_color);
border-radius: 20px;
transition: all 0.3s 0s;
}
/* 開關圓球 */
.switch::after {
content: "";
position: absolute;
top: 1px;
left: 1px;
width: 18px;
height: 18px;
border-radius: 18px;
background-color: white;
transition: all 0.3s 0s;
}
input[type="checkbox"]:checked + .switch::after {
transform: translateX(20px);
}
input[type="checkbox"]:checked + .switch {
background-color: var(--act_color);
}
核心知識點
隱藏真實input輸入框,通過label for屬性與input輸入框綁定。
label標籤本身作爲橢圓形背景,用僞類作爲開關圓球。
input選中後,需要單獨設置label標籤本體和僞類的移動
🌟本系列旨在通過最直接的事例最完整的代碼,解決一些開發中常遇到的實際問題。
例子鏈接🚀:https://github.com/TianYiYang0225/high-ku/tree/master/customSwitch
喜歡的朋友可以點擊關注一波~每天都會更新最實用的項目技巧
有興趣的小夥伴可以關注一下我的公衆號,互相學習,共同進步。