這邊紀錄一下怎麼使用純 CSS 把 checkbox 變成開關元件(toggle switch)。
首先準備一下 CSS,一樣用 label 把 checkbox 包起來。
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
CSS 的部分這是讓 checkbox 看不到,再利用點選狀態利用無中生有產出開關的按鈕。
.switch {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 2px;
top: 2px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: green;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
懂 CSS 的朋友可以調整一下參數調整大小跟顏色那些的。
完整的 code