扫码关注官方订阅号
这种功能怎么实现?
光阴似箭催人老,日月如移越少年。
用绑定不同class的方法来做:
<span v-bind:class="{'left': isClose, 'right': isOpen} switcher" v-on:click="switcher"></span> <!--这个span就是圆形开关,点击的时候触发switcher方法-->
在vue实例中写入标记和开关方法:
data: { isClose: true, isOpen: false//假设默认关闭 }, methods: { switcher: function() { //实现开关切换 isClose = !isClose; isOpen = !isOpen; } }
css样式:
.switcher { transition: left 0.8s; } .left { left: 0; } .right { left: 50px;//移动50px }
这样就能通过点击时改变css属性,并配合transition来实现动态开关了。
上一个小 demo ,引入方式自行修改
switch.html
<p class="switch"> <span class="switch-input"> <input type="checkbox" :false-value=0 :true-value=1 v-model="val"> <span class="input-box"></span> </span> <p class="switch-label"><slot></slot></p> </p>
switch.js
/* switch切换 */ var vue = require('vue.js'); module.exports = vue.component('switch',{ template:__inline('./switch.html'), props:{ val:{ type:[Number,String], require:true, twoWay: true } }, data:function(){ return {}; } });
switch.less
.switch { display: inline-flex; flex-direction: row; align-items: center; vertical-align: middle; .switch-input{ position: relative; width: 52px; height: 32px; input{ position: absolute; left: 0; top: 0; width: 50px; height: 30px; z-index: 99; cursor: pointer; display: inline-block; -webkit-appearance: none; -moz-appearance: none; appearance: none; opacity: 0; &:focus{ outline: none; } } input:checked + .input-box{ border-color: #26a2ff; background-color: #26a2ff; &::before { -webkit-transform: scale(0); transform: scale(0); } &::after { -webkit-transform: translateX(20px); transform: translateX(20px); } } .input-box { position: absolute; cursor: pointer; width: 52px; height: 32px; border: 1px solid #d9d9d9; outline: 0; border-radius: 16px; box-sizing: border-box; background: #d9d9d9; &::after, &::before{ content: ""; top: 0; left: 0; position: absolute; -webkit-transition: -webkit-transform .3s; transition: -webkit-transform .3s; transition: transform .3s; transition: transform .3s, -webkit-transform .3s; border-radius: 15px; } &::after{ width: 30px; height: 30px; background-color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .4); } &::before{ width: 50px; height: 30px; background-color: #fdfdfd; } } } .switch-label { margin-left: 10px; display: inline-block; &:empty { margin-left: 0; } } }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
用绑定不同class的方法来做:
在vue实例中写入标记和开关方法:
css样式:
这样就能通过点击时改变css属性,并配合transition来实现动态开关了。
上一个小 demo ,引入方式自行修改
switch.html
switch.js
switch.less