起因:要实现设计的开关样式,如下图
额,好吧,这样确实挺好看的,我已经用了element ui了,element ui里面没有这种开关样式,那就自己撸了,
撸的时候发现,css里面还有函数attr()和var(),具体这个css函数怎么玩的自己可以查一查,还挺有意思的,
css中:attr() 函数返回选择元素的属性值,var() 函数用于插入自定义的属性值,
怎么然后我就各种用它们两个整了个这个开关组件:
<template> <div> <input class="my-switch" type="checkbox" :style="{'--activeColor':activeColor,'--inactiveColor':inactiveColor}" :activeText="activeText" :inactiveText="inactiveText" :checked="checkedValue" @click="toggleClick" /> </div> </template> <script> export default { props: { checkedValue: { type: Boolean, default: false, }, activeText: { type: String, default: "启动", }, activeColor: { type: String, default: "#409eff", }, inactiveText: { type: String, default: "禁用", }, inactiveColor: { type: String, default: "#f77463", }, }, methods: { toggleClick(e) { this.$emit("toggleClick", e.target.checked); }, }, }; </script> <style scoped> .my-switch { position: relative; width: 52px; height: 20px; border: 2px solid var(--activeColor); outline: 0; border-radius: 0; transition: background-color 0.1s, border 0.1s; appearance: none; outline: 0; background-color: var(--activeColor); border-radius: 15px; box-sizing: content-box; vertical-align: middle; cursor: pointer; } .my-switch:after { content: attr(activeText); color: var(--activeColor); font-size: 8px; line-height: 20px; text-align: center; position: absolute; top: 0; left: 0; width: 30px; height: 20px; border-radius: 15px; background-color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35); } .my-switch:checked:after { content: attr(inactiveText); color: var(--inactiveColor); transform: translateX(22px); } .my-switch:checked { border-color: var(--inactiveColor); background-color: var(--inactiveColor); } </style>
用法示例:
<mySwitch active-text="是" inactive-text="否" :checkedValue="!switchForm.binding" @toggleClick="changeBindingStatus" ></mySwitch> //引入组件 import mySwitch from "@/components/MySwitch/index.vue"; export default { name: 'app', data() { return { switchForm:{binding:false} } }, components: { mySwitch }, methods: { changeBindingStatus(data) { console.log(data); } } }
<mySwitch active-text="是" inactive-text="否" active-color="red" inactive-color="red" :checkedValue="!switchForm.binding" @toggleClick="changeBindingStatus" ></mySwitch>