用vue实现弹窗抖动
使用Vue实现弹窗抖动效果
弹窗抖动是一种常见的交互效果,可以通过CSS动画或JavaScript动态样式实现。以下是两种在Vue中实现弹窗抖动的方案:

方案一:CSS动画实现
创建一个抖动的CSS动画关键帧,通过Vue动态绑定类名触发动画。

<template>
<div class="modal" :class="{ 'shake-animation': isShaking }" @click="stopShaking">
点击停止抖动
</div>
<button @click="startShaking">开始抖动</button>
</template>
<script>
export default {
data() {
return {
isShaking: false
}
},
methods: {
startShaking() {
this.isShaking = true
},
stopShaking() {
this.isShaking = false
}
}
}
</script>
<style>
.modal {
width: 200px;
height: 100px;
background: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
margin: 20px auto;
}
.shake-animation {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) infinite;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
</style>
方案二:JavaScript动态样式
通过ref获取DOM元素,使用setInterval动态修改样式实现抖动。
<template>
<div ref="modal" class="modal" @click="stopShaking">
点击停止抖动
</div>
<button @click="startShaking">开始抖动</button>
</template>
<script>
export default {
methods: {
startShaking() {
this.shakeInterval = setInterval(() => {
const randomX = (Math.random() * 10) - 5
this.$refs.modal.style.transform = `translateX(${randomX}px)`
}, 50)
},
stopShaking() {
clearInterval(this.shakeInterval)
this.$refs.modal.style.transform = 'translateX(0)'
}
},
beforeUnmount() {
clearInterval(this.shakeInterval)
}
}
</script>
<style>
.modal {
width: 200px;
height: 100px;
background: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
margin: 20px auto;
transition: transform 0.1s;
}
</style>
方案三:使用第三方库
如果需要更复杂的动画效果,可以考虑使用动画库如Animate.css或GSAP。
<template>
<div class="modal animate__animated" :class="{ 'animate__headShake': isShaking }">
抖动弹窗内容
</div>
<button @click="toggleShaking">切换抖动</button>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
isShaking: false
}
},
methods: {
toggleShaking() {
this.isShaking = !this.isShaking
}
}
}
</script>
以上三种方案均可实现弹窗抖动效果,CSS动画方案性能最佳,JavaScript方案控制更灵活,第三方库方案实现最简单。根据项目需求选择合适的实现方式。






