起因:要實現設計的開關樣式,如下圖
額,好吧,這樣確實挺好看的,我已經用了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>