css3点击开关按钮
导读:CSS3点击开关按钮是一种非常常见的交互效果,可以用于网站、应用程序等各种场景。本文将介绍如何通过CSS3实现这一效果。/* HTML */<div class="switch"><input type="checkbox...
CSS3点击开关按钮是一种非常常见的交互效果,可以用于网站、应用程序等各种场景。本文将介绍如何通过CSS3实现这一效果。
/* HTML */div class="switch">
input type="checkbox" class="switch-input" id="switch">
label for="switch" class="switch-label">
span class="switch-text-on">
ON/span>
span class="switch-text-off">
OFF/span>
/label>
span class="switch-handle">
/span>
/div>
/* CSS */.switch {
position: relative;
display: inline-block;
line-height: 1;
vertical-align: middle;
width: 60px;
height: 30px;
}
.switch-input {
position: absolute;
top: 0;
left: 0;
opacity: 0;
width: 0;
height: 0;
}
.switch-label {
display: block;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
width: 100%;
height: 100%;
background-color: #ccc;
border-radius: 30px;
transition: background-color 0.3s;
}
.switch-text-on,.switch-text-off {
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 10px;
font-weight: bold;
color: #fff;
opacity: 0.5;
transition: opacity 0.3s;
}
.switch-text-off {
opacity: 1;
}
.switch-input:checked + .switch-label {
background-color: #8bc34a;
}
.switch-input:checked + .switch-label .switch-text-on {
opacity: 1;
}
.switch-input:checked + .switch-label .switch-text-off {
opacity: 0;
}
.switch-handle {
display: block;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 20px;
height: 20px;
background-color: #fff;
border-radius: 50%;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
transition: left 0.3s;
}
.switch-input:checked + .switch-label .switch-handle {
left: calc(100% - 20px);
}
在HTML代码中,我们使用了一个元素来作为开关按钮的容器,其中包含了一个元素和一个元素。其中,元素的type为checkbox,而元素的for属性与元素的id相同,这样当用户点击元素时,就可以同时影响元素的选中状态。
在CSS代码中,我们使用了很多技巧来实现开关按钮的样式,比如使用了伪元素、过渡效果、背景颜色等。其中,最核心的就是使用了伪类选择器:checked来判断元素是否被选中,从而实现开关按钮的切换效果。
总的来说,通过这个实例,我们可以学习到如何通过CSS3来实现一个简单的点击开关按钮交互效果,也可以拓展自己的CSS3技能。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: css3点击开关按钮
本文地址: https://pptw.com/jishu/449671.html
