用vue实现弹窗抖动
使用 Vue 实现弹窗抖动效果
弹窗抖动是一种常见的交互效果,通常用于提示用户操作或吸引注意力。以下是两种实现方法,分别基于 CSS 动画和 JavaScript 动画库。
方法一:使用 CSS 动画
通过 Vue 绑定动态类名,结合 CSS @keyframes 实现抖动效果。
模板部分
<template>
<div class="modal" :class="{ 'shake': isShaking }" @click="shakeModal">
<div class="modal-content">
<p>点击弹窗触发抖动</p>
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
isShaking: false
};
},
methods: {
shakeModal() {
this.isShaking = true;
setTimeout(() => {
this.isShaking = false;
}, 500); // 动画持续时间
}
}
};
</script>
样式部分
<style>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
border: 1px solid #ccc;
border-radius: 8px;
}
.shake {
animation: shake 0.5s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
}
@keyframes shake {
0%, 100% { transform: translate(-50%, -50%); }
10%, 30%, 50%, 70%, 90% { transform: translate(-51%, -50%); }
20%, 40%, 60%, 80% { transform: translate(-49%, -50%); }
}
</style>
方法二:使用 GSAP 动画库
GSAP 提供更灵活的动画控制,适合复杂抖动效果。

安装 GSAP
npm install gsap
模板部分
<template>
<div class="modal" ref="modal" @click="shakeModal">
<div class="modal-content">
<p>点击弹窗触发抖动</p>
</div>
</div>
</template>
脚本部分

<script>
import { gsap } from "gsap";
export default {
methods: {
shakeModal() {
gsap.to(this.$refs.modal, {
x: -10,
duration: 0.1,
repeat: 5,
yoyo: true,
onComplete: () => {
gsap.set(this.$refs.modal, { x: 0 });
}
});
}
}
};
</script>
样式部分
<style>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
border: 1px solid #ccc;
border-radius: 8px;
}
</style>
注意事项
-
性能优化
CSS 动画性能通常优于 JavaScript 动画,适合简单效果。GSAP 适合需要精细控制的场景。 -
浏览器兼容性
CSStransform和animation在现代浏览器中支持良好,旧版本需加前缀(如-webkit-)。 -
交互逻辑
可通过v-if或v-show控制弹窗显示,抖动作为附加效果。
以上方法可根据实际需求调整参数(如抖动幅度、持续时间)。






