js实现动画
使用CSS动画实现简单效果
通过@keyframes定义动画关键帧,结合element.style.animation属性控制播放。适合简单过渡效果(如渐变、位移)。

// 定义CSS动画
const style = document.createElement('style');
style.innerHTML = `
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
`;
document.head.appendChild(style);
// 应用动画
const element = document.getElementById('target');
element.style.animation = 'fadeIn 2s ease-in-out';
使用requestAnimationFrame实现高性能动画
通过递归调用requestAnimationFrame实现逐帧控制,适合复杂动画(如游戏、物理模拟)。

let startTime = null;
function animate(timestamp) {
if (!startTime) startTime = timestamp;
const progress = timestamp - startTime;
// 计算动画状态(例如旋转角度)
const rotation = (progress / 1000) * 360; // 1秒旋转360度
element.style.transform = `rotate(${rotation}deg)`;
if (progress < 2000) { // 动画持续2秒
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
使用GSAP等动画库
GSAP提供更强大的时间轴控制和复杂动画序列。适合需要精细管理的场景。
// 安装GSAP后使用
gsap.to("#target", {
duration: 1,
x: 100,
rotation: 360,
ease: "bounce.out"
});
使用Web Animations API
原生API支持组合动画和精确控制,兼容现代浏览器。
const element = document.getElementById('target');
element.animate(
[
{ transform: 'translateX(0px)', opacity: 1 },
{ transform: 'translateX(100px)', opacity: 0.5 }
],
{
duration: 800,
easing: 'ease-in-out',
iterations: Infinity
}
);
性能优化建议
- 优先使用CSS动画或
transform/opacity属性(触发硬件加速)。 - 避免频繁操作DOM或触发重排(如读取
offsetHeight)。 - 使用
will-change提示浏览器优化:.target { will-change: transform, opacity; }






