vue实现动态高度抖动
实现动态高度抖动的方案
在Vue中实现动态高度抖动效果,可以通过CSS动画或JavaScript动画库实现。以下是几种常见方法:
使用CSS关键帧动画
通过定义@keyframes创建抖动动画,动态绑定高度值:

<template>
<div
class="shake-box"
:style="{ height: currentHeight + 'px' }"
@click="startShake"
></div>
</template>
<script>
export default {
data() {
return {
currentHeight: 100,
isShaking: false
}
},
methods: {
startShake() {
if(this.isShaking) return;
this.isShaking = true;
let baseHeight = 100;
let interval = setInterval(() => {
this.currentHeight = baseHeight + Math.random() * 20 - 10;
}, 50);
setTimeout(() => {
clearInterval(interval);
this.currentHeight = baseHeight;
this.isShaking = false;
}, 1000);
}
}
}
</script>
<style>
.shake-box {
width: 200px;
background-color: #42b983;
transition: height 0.05s ease-out;
}
</style>
使用GSAP动画库
GSAP提供更强大的动画控制能力:
import { gsap } from 'gsap';
methods: {
gsapShake() {
const el = this.$el.querySelector('.shake-box');
gsap.to(el, {
height: () => 100 + Math.random() * 30 - 15,
duration: 0.1,
repeat: 5,
yoyo: true,
onComplete: () => {
gsap.to(el, { height: 100, duration: 0.2 });
}
});
}
}
使用CSS自定义属性
结合CSS变量实现平滑过渡:

<template>
<div
class="css-var-shake"
:style="{'--shake-height': heightVar}"
@mouseenter="triggerShake"
></div>
</template>
<script>
export default {
data() {
return {
heightVar: '100px'
}
},
methods: {
triggerShake() {
const values = ['90px', '110px', '95px', '105px', '100px'];
values.forEach((val, i) => {
setTimeout(() => {
this.heightVar = val;
}, i * 100);
});
}
}
}
</script>
<style>
.css-var-shake {
width: 200px;
height: var(--shake-height);
background-color: #ff7043;
transition: height 0.1s cubic-bezier(0.4, 0, 0.2, 1);
}
</style>
响应式高度抖动组件
创建可复用的抖动组件:
// ShakeHeight.vue
export default {
props: {
baseHeight: { type: Number, default: 100 },
intensity: { type: Number, default: 10 },
duration: { type: Number, default: 500 }
},
render() {
return this.$scopedSlots.default({
height: this.currentHeight,
startShake: this.startShake
});
},
data() {
return {
currentHeight: this.baseHeight
}
},
methods: {
startShake() {
const startTime = Date.now();
const animate = () => {
const elapsed = Date.now() - startTime;
const progress = elapsed / this.duration;
if(progress < 1) {
this.currentHeight = this.baseHeight +
Math.sin(progress * Math.PI * 10) * this.intensity;
requestAnimationFrame(animate);
} else {
this.currentHeight = this.baseHeight;
}
};
animate();
}
}
}
使用示例:
<ShakeHeight v-slot="{ height, startShake }">
<div
:style="{ height: height + 'px' }"
@click="startShake"
class="shake-item"
></div>
</ShakeHeight>
性能优化建议
- 使用
will-change: height提示浏览器优化 - 避免在抖动期间触发重排操作
- 对于复杂场景考虑使用Web Animation API
- 移动端注意减少动画强度保证流畅性
以上方案可根据具体需求选择,CSS方案适合简单场景,GSAP适合复杂动画,组件化方案便于复用。






