js实现回弹
实现回弹效果的JavaScript方法
使用CSS动画结合JavaScript可以轻松实现回弹效果。以下是两种常见方法:
使用CSS关键帧动画
通过定义@keyframes创建回弹动画,JavaScript控制触发时机:
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
const element = document.getElementById('bounceElement');
element.addEventListener('click', () => {
element.style.animation = 'bounce 0.5s ease';
setTimeout(() => element.style.animation = '', 500);
});
使用JavaScript动态计算位置
通过requestAnimationFrame实现更精细的控制:
function bounce(element, height = 20, duration = 500) {
let start = null;
const animate = (timestamp) => {
if (!start) start = timestamp;
const progress = (timestamp - start) / duration;
const y = height * Math.sin(progress * Math.PI * 2);
element.style.transform = `translateY(${-Math.abs(y)}px)`;
if (progress < 1) requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
}
物理引擎实现高级回弹
对于更真实的物理效果,可以模拟弹性系数和阻尼:
function physicsBounce(element, options = {}) {
const { stiffness = 0.1, damping = 0.8 } = options;
let position = 0, velocity = 0, target = 0;
function update() {
const force = -stiffness * position;
velocity += force;
velocity *= damping;
position += velocity;
element.style.transform = `translateY(${position}px)`;
if (Math.abs(velocity) > 0.01) requestAnimationFrame(update);
}
function trigger() {
velocity = -15;
update();
}
return { trigger };
}
第三方库解决方案
使用现成的动画库可以快速实现复杂效果:
- GSAP:
TweenMax.to(element, 0.5, { y: -20, ease: Bounce.easeOut }) - Anime.js:内置弹性缓动函数
- Popmotion:提供完整的物理动画系统
移动端优化技巧
针对触摸事件需要特别处理:

let startY, isBouncing = false;
element.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
element.addEventListener('touchmove', (e) => {
if (isBouncing) return;
const deltaY = e.touches[0].clientY - startY;
if (deltaY < -10) triggerBounce();
});






