vue3+ts制作玻璃风格的开关按钮效果


崧峻
原创
发布时间: 2026-01-27 16:56:52 | 阅读数 0收藏数 0评论数 0
封面
在现代网页设计中,玻璃风(Glassmorphism)风格因其半透明、模糊背景和轻量感而备受欢迎。本篇文章将使用 Vue 3 + TypeScript 实现一个 玻璃风格开关按钮。教程会教你如何通过 CSS 的 backdrop-filter、透明度和阴影效果打造玻璃质感,同时利用 Vue 的响应式 ref 控制开关状态。滑块在切换时带有平滑过渡动画,让按钮更生动。通过 SCSS 变量,你还可以轻松调整大小、颜色和光影,使组件更易维护和扩展。最终效果是一个可点击的现代感开关,适合仪表盘、设置面板或高颜值网站界面,让你的 UI 更有质感与交互感。
1

创建vue文件

如图所示创建一个vue 文件名为GlassSwitch.vue

2

vue文件内容


代码内容如下

<script setup lang="ts">
import type {Ref} from "vue";

const model: Ref<boolean> = defineModel( {type: Boolean, default: true});

</script>

<template>
<button class="glass-switch" @click="model =!model" :class="`${model?'active':'notActive'}`">
<span class="glass-switch-thumb"/>
</button>
</template>


<style scoped lang="scss">
// 开关的边框
.glass-switch {
// 滑块宽度
--thumb-size: 20px;
position: relative;
width: 48px;
height: 27px;
background: rgba(255, 255, 255, 0.08);
border-radius: 13px;
border: 1.5px solid rgba(255, 255, 255, 0.12);
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
}

// 选中样式
.glass-switch.active {
background: rgba(255, 255, 255, 0.16);
backdrop-filter: blur(30px) saturate(150%);
-webkit-backdrop-filter: blur(30px) saturate(150%);
border-color: rgba(255, 255, 255, 0.25);
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.15),
inset 0 2px 3px rgba(255, 255, 255, 0.45);
}

// 滑块公共样式
.glass-switch-thumb {
width: var(--thumb-size);
height: var(--thumb-size);
border-radius: 50%;
transition: left 0.3s ease;
}

// 选中时候的滑块样式
.glass-switch.active .glass-switch-thumb {
position: absolute;
top: 2px;
left: calc(100% - var(--thumb-size) - 2px);
background: linear-gradient(135deg, rgba(255, 255, 255, 0.7), rgba(255, 255, 255, 0.55));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
}

// 未选中的滑块样式
.glass-switch.notActive .glass-switch-thumb {
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background: linear-gradient(135deg, rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.3));
position: absolute;
top: 2px;
left: 2px;
}
</style>





3

如何使用?


<script setup lang="ts">
import {ref} from "vue";
import GlassSwitch from "@/components/glass/GlassSwitch.vue";


const t = ref(false);
</script>

<template>
<div style="height: 2000px;display: flex;align-items: center;justify-content: center">

<GlassSwitch v-model="t"/>

</div>
</template>

<style scoped lang="scss">

</style>


4

效果演示

效果演示看视频

阅读记录0
点赞0
收藏0
禁止 本文未经作者允许授权,禁止转载
猜你喜欢
评论/提问(已发布 0 条)
评论 评论
收藏 收藏
分享 分享
pdf下载 下载
pdf下载 举报