我们在平时开发业务的时候,一般都是直接用第三方组件库,比如elementUI,antdesign等。以至于我们越来越废,离开这些组件库,基本上就不会开发了。这样很危险,很容易成为所谓的cv工程师。而本人是非常喜欢去自己实现一些有趣的东西的,今天就来手动实现一个Switch组件,效果如下
首先我们不借助任何框架实现一个
- 首先是html结构
<div>
<input type="checkbox" id="checkbox" class="checkbox"/>
<label for="checkbox" class="switch">复选框</label>
</div>
效果如下
我们接下来需要修改样式,将本身的CheckBox隐藏,给label设置宽高,背景色等,删掉label标签中的文本
.checkbox {
display: none;
}
.switch {
width: 40px;
height: 20px;
background: #dcdfe6;
border-radius: 10px;
display: inline-block;
position: relative;
}
效果如下
接下来我们加会左右移动的滑块,给label元素加一个伪元素
.switch::after {
content: "";
position: absolute;
width: 16px;
height: 16px;
border-radius: 100%;
background: #fff;
top: 1px;
left: 1px;
}
接下来就是让CheckBox选中时,滑块移动到右边,并且背景色变为蓝色我们可以使用复选框的checked伪类来实现
checkbox:checked + .switch {
background-color: #409eff;
}
.checkbox:checked + .switch::after {
left: 20px;
}
现在可以切换了,但是没有动画,切换起来比较生硬,下面加个动画,这样一个简单的Switch效果就实现了
switch::after {
...
transition: all .3s;
}
这种方式有个缺点,就是每次使用都需要给CheckBox加个id,这样很容易重名,改进方式可以用js来控制复选框的选中状态,这里不再赘述,下面我们基于vue来写一个
<!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">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<style>
.checkbox {
display: none;
}
.switch {
width: 40px;
height: 20px;
background: #dcdfe6;
border-radius: 10px;
display: inline-block;
position: relative;
cursor: pointer;
}
.switch::after {
content: "";
position: absolute;
left:0;
width: 16px;
height: 16px;
border-radius: 100%;
background: #fff;
top: 1px;
left: 1px;
transition: all 0.3s;
}
.checked {
background: #409eff;;
}
.checked::after {
left: 20px;
}
</style>
</head>
<body>
<div id="app">
<input type="checkbox" v-model="checked" class="checkbox"/>
<span class="switch" :class="{checked: checked}" @click="toggle">
</span>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
checked: false
},
methods: {
toggle() {
this.checked = !this.checked
}
},
})
</script>
</html>
可以看到基于vuejs的实现,就要合理得多,而且很容易封装组件复用