js实现晃动
实现元素晃动效果的方法
使用CSS动画结合JavaScript触发晃动效果是一种常见方式。以下是一个简单的实现方案:
CSS部分
.shake {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}
@keyframes shake {
10%, 90% { transform: translate3d(-1px, 0, 0); }
20%, 80% { transform: translate3d(2px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
40%, 60% { transform: translate3d(4px, 0, 0); }
}
JavaScript部分
function shakeElement(element) {
element.classList.add('shake');
element.addEventListener('animationend', () => {
element.classList.remove('shake');
}, {once: true});
}
// 使用示例
const button = document.querySelector('#myButton');
button.addEventListener('click', () => shakeElement(button));
物理模拟晃动效果
使用requestAnimationFrame实现更自然的物理晃动:
function physicsShake(element, intensity = 10, decay = 0.8) {
let x = 0;
let velocity = intensity;
const originalX = element.offsetLeft;
function animate() {
x += velocity;
velocity *= -decay;
element.style.transform = `translateX(${x}px)`;
if (Math.abs(velocity) > 0.1) {
requestAnimationFrame(animate);
} else {
element.style.transform = '';
}
}
animate();
}
使用GSAP库实现高级晃动
GSAP提供更强大的动画控制:
// 引入GSAP后使用
gsap.to(element, {
x: "+=10",
repeat: 5,
yoyo: true,
duration: 0.1,
ease: "power1.inOut"
});
响应式晃动组件实现
创建一个可复用的晃动组件类:
class Shaker {
constructor(element) {
this.element = element;
}
shake(options = {}) {
const {
intensity = 10,
duration = 500,
decay = 0.85
} = options;
const startTime = performance.now();
const animate = (time) => {
const elapsed = time - startTime;
const progress = elapsed / duration;
if (progress >= 1) {
this.element.style.transform = '';
return;
}
const shakeValue = intensity * Math.sin(progress * 20) * (1 - progress);
this.element.style.transform = `translateX(${shakeValue}px)`;
requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
}
}
// 使用示例
const shaker = new Shaker(document.getElementById('element'));
shaker.shake({ intensity: 15, duration: 1000 });
注意事项
- 晃动动画应考虑性能影响,避免在低端设备上过度使用
- 晃动幅度应根据元素大小和使用场景适当调整
- 确保晃动结束后元素恢复原始位置
- 移动端设备可能需要调整晃动参数以获得更好的触觉反馈效果







