今天就用css做一个入门级的滑动开关,比较简单,容易实现
bady 里代码的设置
<body> <div class="switch"> <label> <input type="checkbox" name="checkboxswitch" class="onoff"> </label> </div> </body>
1、选择前位置大小的设置(即滑动的范围)
.onoff::before{ content: ""; display: block; 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;
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{ 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; 40px; height: 24.5px; border-radius: 25px; margin-left: -23px; margin-top: -4px; } .onoff::after{ content: ""; display: block; 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>