【css】簡單滑動開關(每日一技)
阿新 • • 發佈:2020-08-17
今天就用css做一個入門級的滑動開關,比較簡單,容易實現
bady 裡程式碼的設定
<body> <div class="switch"> <label> <input type="checkbox" name="checkboxswitch" class="onoff"> </label> </div> </body>
1、選擇前位置大小的設定(即滑動的範圍)
.onoff::before{ content: ""; display: block; width: 40px;/* 滑動範圍設定 */ height: 24.5px; border: 1px solid rgb(156, 155, 155); background-color: rgb(179, 176, 176); border-radius: 25px;/* 圓角設定 */ margin-left: -23px;/* 位置的調整 */ margin-top: -4px; }
2、按鈕選擇前位置的設定
.onoff::after{
content: "";
display: block;
width: 25px;/* 按鈕大小 */
height: 25px;
background-color: rgb(255, 255, 255);
margin-left: -22px;/* 按鈕位置調整 */
margin-top: -26px;
transition: margin 0.2s ease-in 0.2s;/* 變化速度與方式 */
border-radius: 25px;/* 圓角設定 */
}
3、其實整個實現的過程就是選擇前後按鈕位置發生的變化,根據調整讓按鈕在範圍內變化,從而達到滑動的效果
.onoff:checked::after{ margin-left:-7px; }
上面的程式碼已經可以簡單的實現滑動按鈕的效果,可以根據自己的喜歡在做修改,下面是我做簡單優化後的效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>開關樣式</title> <style> *{ margin: 0; padding: 0; } .switch{ width: 700px; height: 50px; background-color: rgb(238, 237, 237); margin: 100px 100px; padding: 20px 50px; } span{ margin-left: 15px; margin-right: 50px; font-weight: 200; opacity: 0.8; } .onoff::before{ content: ""; display: block; width: 40px; height: 24.5px; border-radius: 25px; margin-left: -23px; margin-top: -4px; } .onoff::after{ content: ""; display: block; width: 25px; height: 25px; background-color: rgb(255, 255, 255); margin-left: -22px; margin-top: -26px; transition: margin 0.2s ease-in 0.2s; border-radius: 25px; } .onoff:checked::after{ margin-left:-7px; } .sw1::before{ border: 1px solid rgb(156, 155, 155); background-color: rgb(179, 176, 176); } .sw2::before{ border: 1px solid rgb(127, 154, 241); background-color: rgb(127, 154, 241); } .sw3::before{ border: 1px solid rgb(144, 253, 129); background-color: rgb(144, 253, 129); } .sw4::before{ border: 1px solid rgb(255, 138, 138); background-color: rgb(255, 138, 138); } </style> </head> <body> <div class="switch"> <label> <input type="checkbox" name="checkboxswitch" class="onoff sw1" checked><span>switch large</span> <input type="checkbox" name="checkboxswitch" class="onoff sw2" checked><span>switch large</span> <input type="checkbox" name="checkboxswitch" class="onoff sw3" checked><span>switch large</span> <input type="checkbox" name="checkboxswitch" class="onoff sw4" checked><span>switch large</span> </label> </div> </body> </html>