我们有很多放式实现switch开关的效果,平时大多数情况都是用第三方组件来实现的,虽然现在组件的定制性越来越高,但是想要一些特殊的效果还是得依靠原生来实现。那么接下来我们实现一个简单的switch开关效果吧。
效果:
代码:
实现思路:设置一个type="checkbox"的input框让其不展示,但是点击时选中状态会变,然后根据选中状态来控制下面真正展示的label 标签的展示样式即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
width: 43px;
margin-left: 50%;
margin-top: 20%;
}
.switch{
display:none;
}
label{
position:relative;
display: block;
padding: 1px;
border-radius: 24px;
height: 22px;
margin-bottom: 15px;
background-color: rgb(22, 20, 155);
cursor: pointer;
vertical-align: top;
-webkit-user-select: none;
/* user-select:none;表示文本不能被选中。 */
}
label:before{
content: '';
display: block;
border-radius: 24px;
height: 22px;
background-color: white;
-webkit-transform: scale(1, 1);
-webkit-transition: all 0.3s ease;
}
label:after{
content: '';
position: absolute;
top: 50%;
left: 50%;
margin-top: -11px;
margin-left: -11px;
width: 22px;
height: 22px;
border-radius: 22px;
background-color: white;
box-shadow: 1px 1px 1px 1px rgba(0,0,0,0.08);
-webkit-transform: translateX(-9px);
-webkit-transition: all 0.3s ease;
}
/* A~B{ }表示A之后出现的所有B,且A、B有相同的父元素 */
.switch:checked~label:after{
-webkit-transform: translateX(9px);
}
.switch:checked~label:before{
background-color:rgb(128, 26, 0);
}
</style>
</head>
<body>
<div class="container">
<div class="bg_con">
<input id="checked_1" type="checkbox" class="switch" />
<label for="checked_1"></label>
<!-- for和id成对出现时,for属性中的值和绑定id的值一样,点击for里面的元素,跳转到响应的绑定的id标签那里 -->
</div>
</div>
</body>
</html>