如何通过代码实现元素抽动运动动画效果
元素随机抽动交互效果实现
核心逻辑匹配
- 元素默认静止,无常驻动画
- 随机间隔触发快速旋转抽动,动画完成后自动回归初始状态
- 支持鼠标悬停触发1秒剧烈抖动的扩展交互
完整代码
样式代码
.target { /* 替换为目标元素的实际样式即可 */ width: 80px; height: 80px; background: #2563eb; border-radius: 8px; margin: 80px auto; will-change: transform; } /* 随机抽动动画 */ @keyframes twitch { 0% { transform: rotate(0); } 25% { transform: rotate(-12deg); } 50% { transform: rotate(10deg); } 75% { transform: rotate(-5deg); } 100% { transform: rotate(0); } } .is-twitching { animation: twitch 0.28s ease-in-out forwards; } /* 悬停剧烈抖动动画 */ @keyframes hardShake { 0% { transform: translate(0,0) rotate(0); } 10% { transform: translate(-5px,-3px) rotate(-7deg); } 20% { transform: translate(5px,3px) rotate(7deg); } 30% { transform: translate(-4px,2px) rotate(-5deg); } 40% { transform: translate(4px,-2px) rotate(5deg); } 50% { transform: translate(-3px,1px) rotate(-3deg); } 60% { transform: translate(3px,-1px) rotate(3deg); } 70% { transform: translate(-2px,1px) rotate(-2deg); } 80% { transform: translate(2px,-1px) rotate(2deg); } 90% { transform: translate(-1px,0) rotate(-1deg); } 100% { transform: translate(0,0) rotate(0); } } .is-shaking { animation: hardShake 1s ease-in-out forwards; }
逻辑代码
const targetEl = document.querySelector('.target'); // 随机触发抽动 function triggerRandomTwitch() { // 随机间隔2-7秒触发一次,可自行调整频率 const randomDelay = Math.random() * 5000 + 2000; setTimeout(() => { // 悬停抖动过程中不触发随机抽动,避免动画冲突 if (!targetEl.classList.contains('is-shaking')) { targetEl.classList.add('is-twitching'); // 动画结束后移除状态类,回归静止 setTimeout(() => targetEl.classList.remove('is-twitching'), 280); } triggerRandomTwitch(); }, randomDelay); } triggerRandomTwitch(); // 悬停触发1秒剧烈抖动 targetEl.addEventListener('mouseenter', () => { targetEl.classList.remove('is-twitching'); targetEl.classList.add('is-shaking'); setTimeout(() => targetEl.classList.remove('is-shaking'), 1000); });
参数调整说明
- 抽动频率:修改
randomDelay的计算范围,数值越小触发越频繁 - 动画幅度:直接修改对应
@keyframes关键帧里的rotate、translate数值即可 - 动画时长:修改animation属性的时长参数,和JS里对应移除类的延时保持一致即可
内容的提问来源于stack exchange,提问作者AlexM
相关产品推荐
相关产品推荐

