思路:
switch需要的元素有:
开关背景、开关按钮。点击按钮后,背景色变化,按钮颜色变化,呈现开关打开状态。利用type=checkbox,来实现switch效果(修改样式)。
细节:
开关背景可以在里面添加个的作为被修改的背景。开关按钮可以用伪元素来实现。- 点击后颜色变化,可以根据checkbox特性,使用
伪类选择器来添加改变背景色的样式,且通过伪类选择器,让伪元素移动位置。
前置知识一:
前置知识二:正常来说,我们dispaly:none的时候,我们就不会触发隐藏元素的点击事件了。
对于type=checkbox,当我们在外层加一个标签,就可以在隐藏input的时候,点击label触发选中事件,我们经常用这种方式来定义一些样式。
<label class="switch">
<input type="checkbox">
<span class="slider">span>
label>
<style>
:root{
--switchWidth:90px;
--switchHeight:40px;
}
/*
前置操作:
1. 外层定义switch的大小。
2. 隐藏checkbox框。
*/
/* 定义开关的大小 */
.switch {
position: relative;
display: inline-block;
width: var(--switchWidth);
height: var(--switchHeight);
}
/* 隐藏原本的复选框 */
.switch input {
display: none;
}
/*
第一步:
1.定义switch的背景:让span标签,填充满父元素,用作switch的背景。
2.定义switch的开关按钮:使用伪元素,给switch添加按钮。position:absolute会找离着自己最近的relative定位。
*/
/* 开关背景 */
.slider {
position: absolute; /* 子绝父相定位 */
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #eee;
transition: .5s; /* 过渡,所有的都0.5S */
border-radius: 100px;
}
/* 开关按钮 */
.slider::before {
content: "";
height: 30px;
width: 30px;
border-radius: 20px;
position: absolute;
left: 8px;
bottom: 5px;
background-color: #aeaaae;
transition: .4s;
}
/*
第二步:
1.选中的时候更改起兄弟元素样式。也就是修改选中的背景色。
2.选中的时候,开关按钮向左移动一段距离且改变颜色。
*/
input:checked + .slider{
background: green;
}
/* 使用伪类与伪元素。当input选中的时候,已经添加的伪类,颜色变白,且移动44px */
input:checked + .slider::before{
background-color: #fff;
transform: translateX(44px);
}
style>
<style>
:root{
--size:200px;
}
.box{
height:var(--size);
width:var(--size);
background:red;
}
.box .item{
height:calc(var(--size)/2);
width:calc(var(--size)/2);
background:green;
}
style>
<div class="box">
<div class="item">div>
div>