让我们先来看看实现的效果
html(包含js)代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>第二十一天</title>
</head>
<body>
<div class="channel">
switch切换按钮啦!
</div>
<div class="container">
<div id="switch" >
<div id="circle"></div>
</div>
</div>
<script>
let swch=document.getElementById('switch');
swch.addEventListener('click',(e)=>{
// swch.classList.toggle('switched');
if(swch.classList.contains('switched')){
swch.classList.remove('switched');
} else{
swch.classList.add('switched');
}
});
</script>
</body>
</html>
css代码
:root {
--background-color: #2c3e50;
--border-color: #7591AD;
--text-color: #34495e;
--color1: #EC3E27;
--color2: #fd79a8;
--color3: #0984e3;
--color4: #00b894;
--color5: #fdcb6e;
--color6: #e056fd;
--color7: #F97F51;
--color8: #BDC581;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html{
font-size: 14px;
}
body{
width: 100vw;
height: 100vh;
background-color: var(--background-color);
display: flex;
justify-content: center;
align-items: center;
font-family: 'Montserrat', sans-serif, Arial, 'Microsoft Yahei';
}
.channel{
position: absolute;
width: 80%;
text-align: center;
top: 10vh;
left: 50%;
transform: translateX(-50%);
font-size: 5vmin;
font-weight:bold ;
color: #353535;
z-index: 10000;
}
.container{
width: 100vw;
height: 100vh;
/* background-color: #00b894; */
display: flex;
justify-content: center;
align-items: center;
}
#switch{
position: absolute;
width: 60px;
height: 30px;
border: 2px solid #333;
border-radius: 30px;
cursor: pointer;
}
#switch::before,
#switch::after{
position: absolute;
line-height: 26px;
text-transform: uppercase;
padding: 0 20px;
cursor: initial;
pointer-events: none;
}
#switch::before{
content: 'slow';
right: 90%;
}
#switch::after{
content: 'fast';
left: 90%;
}
#switch #circle{
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border: 2px solid #333;
border-radius: 50%;
box-shadow: inset 4px -2px 0 0 var(--color8);
transition: all .5s cubic-bezier(.74,1.28,.73,.99);
}
#switch.switched #circle{
left: calc(100% - 20px - 3px);
box-shadow: inset 4px -2px 0 0 var(--color3);
}
设计思路与今日份知识总结
设计思路
我们为什么不用checkbox呢?因为不好看呗!
- 在switch块先画一个圆框
- 在circle画一个圆
- 然后用js控制switch的classList,通过给switch添加点击响应,来改变switch的样式
- 两个样式,一个左边,一个右边就成了
- 细节的改变看下面的知识总结把!
今日份知识总结
有些知识前面多次出现的就不写了哦!
标签 | 作用 |
---|---|
classList.contains | 看当前元素的class是否包含 |
classList.remove | 移除当前元素的某个class属性 |
classList.add | 给当前元素添加某个class属性 |
box-sizing | box-sizing 属性允许您以特定的方式定义匹配某个区域的特定元素。 |
cursor | 定义鼠标的样式 |
pointer-events | 禁止鼠标事件 |
line-height | line-height 属性设置行间的距离(行高) |
cubic-bezier | cubic-bezier() 函数定义了一个贝塞尔曲线(Cubic Bezier)。用来控制变化速度 |