vue实现抖动
Vue 实现抖动效果
在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法:
使用 CSS 动画
通过定义 @keyframes 动画并在 Vue 组件中应用:
<template>
<div :class="{ 'shake': shouldShake }" @click="triggerShake">
点击触发抖动
</div>
</template>
<script>
export default {
data() {
return {
shouldShake: false
}
},
methods: {
triggerShake() {
this.shouldShake = true
setTimeout(() => {
this.shouldShake = false
}, 500)
}
}
}
</script>
<style>
.shake {
animation: shake 0.5s;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
</style>
使用 Vue Transition
Vue 的 <transition> 组件可以配合 CSS 实现抖动:
<template>
<button @click="show = !show">
点击触发
</button>
<transition name="shake">
<div v-if="show" class="box">抖动内容</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.shake-enter-active {
animation: shake 0.5s;
}
.shake-leave-active {
animation: shake 0.5s reverse;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
</style>
使用第三方动画库
安装 animate.css 库:
npm install animate.css
在 Vue 中使用:
<template>
<div class="animated" :class="{ 'shakeX': shouldShake }">
抖动元素
</div>
<button @click="triggerShake">触发抖动</button>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
shouldShake: false
}
},
methods: {
triggerShake() {
this.shouldShake = true
setTimeout(() => {
this.shouldShake = false
}, 1000)
}
}
}
</script>
使用 JavaScript 实现
通过直接操作 DOM 元素的样式:
<template>
<div ref="shakeElement" class="box">
抖动内容
</div>
<button @click="shake">抖动</button>
</template>
<script>
export default {
methods: {
shake() {
const element = this.$refs.shakeElement
let distance = 5
let times = 10
let speed = 50
for (let i = 0; i < times; i++) {
setTimeout(() => {
element.style.transform = `translateX(${distance}px)`
distance = -distance
}, i * speed)
}
setTimeout(() => {
element.style.transform = 'translateX(0)'
}, times * speed)
}
}
}
</script>
这些方法都可以在 Vue 中实现抖动效果,选择适合项目需求的方式即可。CSS 动画性能较好,适合简单效果;JavaScript 实现更灵活;第三方库则提供了更多预设动画。







