最近公司移动端web项目中新增了通知设置功能,需要用到switch开关组件,但该项目没有用到任何的UI组建库,因此需要自己来写一个switch组件,接下来就一步步的实现一个switch开关的组件。
HTML页面结构
<section class='model-15'>
<label class='switch'>
<input type='checkbox'>
<span></span>
</label>
</section>
CSS样式
.switch{
width:40px;
height:20px;
border-radius:30px;
overflow: hidden;
vertical-align:middle;
position:relative;
display: inline-block;
background:#ccc;
box-shadow: 0 0 1px #36a6d4;
}
.switch input{
visibility: hidden;
}
.switch span{
position:absolute;
top:0;
left:0;
border-radius: 50%;
background:#fff;
width:50%;
height:100%;
transition:all linear 0.2s;
}
.switch span::before{
position: absolute;
top:0;
left:-100%;
content:'';
width:200%;
height:100%;
border-radius: 30px;
background:#36a6d4;
}
.switch span::after{
content:'';
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
border-radius: 50%;
background:#fff;
}
.switch input:checked +span{
transform:translateX(100%);
}
实现效果
![](https://img.haomeiwen.com/i4921980/e139100f45f13483.png)
写在最后
以上只是实现了基础的UI效果,但是该组件重点还是在功能实现,基本思路在于根据点击input单选框后会添加checked属性的特性来实现开关的切换。如果使用jQuery这种传统框架,那可能就需要获取到DOM然后控制checked的属性来实现。但我在项目中使用的是Vue,Vue的核心就是数据驱动,因此只需要处理数据层就可以。好了,千言万语不如上代码。
视图层代码
<table border='1'>
<tr>
<th>通知类型</th>
<th>站内消息</th>
<th>微信通知</th>
<th>短信通知</th>
</tr>
<tr v-for='(item, index) in list'>
<td>{{item.title}}</td>
<td>
<section class='model-15'>
<label class='switch'>
<input type='checkbox' class='site' checked v-if='item.status.site === "ON"' @click="handleSwitch(index, 'site', item.status.site)">
<input type='checkbox' class='site' v-else @click="handleSwitch(index, 'site', item.status.site)">
<span></span>
</label>
</section>
</td>
<td>
<section class='model-15'>
<label class='switch'>
<input type='checkbox' class='wechat' checked v-if='item.status.wechat === "ON"' @click="handleSwitch(index, 'wechat', item.status.wechat)">
<input type='checkbox' class='wechat' v-else @click="handleSwitch(index, 'wechat', item.status.wechat)">
<span></span>
</label>
</section>
</td>
<td>
<section class='model-15' v-if='item.label'>
<label class='switch'>
<input type='checkbox' class='sms' checked v-if='item.status.sms === "ON"' @click="handleSwitch(index, 'sms', item.status.sms)">
<input type='checkbox' class='sms' v-else @click="handleSwitch(index, 'sms', item.status.sms)">
<span></span>
</label>
</section>
</td>
</tr>
</table>
因为我这里要控制的开关比较多,其他代码就不一一贴了,无非就是初始化页面时请求数据,根据返回数据状态控制开关,然后点击开关时修改对应开关的状态数据,最后根据数据提交表单。
切换开关改变数据
handleSwitch (index, type, state) {
if (state === 'ON') {
this.list[index].status[type] = 'OFF'
} else {
this.list[index].status[type] = 'ON'
}
},
网友评论