js实现animation
使用CSS动画与JavaScript结合
在JavaScript中可以通过操作CSS的animation属性来实现动画效果。结合@keyframes规则定义动画序列,再通过JavaScript动态添加或修改类名触发动画。
// 定义关键帧
const style = document.createElement('style');
style.innerHTML = `
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
.animate-slide {
animation: slideIn 1s forwards;
}
`;
document.head.appendChild(style);
// 触发动画
const element = document.getElementById('target');
element.classList.add('animate-slide');
使用requestAnimationFrame实现高性能动画
requestAnimationFrame是浏览器原生API,适合需要精细控制的动画场景。该方法会在浏览器重绘前执行回调函数,确保动画流畅性。

let start = null;
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const element = document.getElementById('target');
element.style.transform = `translateX(${Math.min(progress / 10, 100)}px)`;
if (progress < 1000) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
使用Web Animations API
现代浏览器支持的Web Animations API提供了更强大的动画控制能力,支持时间轴、组合动画等高级特性。
const element = document.getElementById('target');
element.animate([
{ transform: 'scale(1)', opacity: 1 },
{ transform: 'scale(1.5)', opacity: 0.5 }
], {
duration: 1000,
iterations: Infinity,
direction: 'alternate'
});
使用第三方动画库
对于复杂动画场景,可以考虑使用专业动画库如GSAP、Anime.js等。这些库提供了丰富的动画效果和跨浏览器兼容性。

// 使用GSAP示例
gsap.to("#target", {
x: 100,
duration: 1,
ease: "bounce.out"
});
处理动画事件
JavaScript可以监听动画相关事件,实现动画状态控制或链式动画效果。
const element = document.getElementById('target');
element.addEventListener('animationstart', () => {
console.log('动画开始');
});
element.addEventListener('animationend', () => {
console.log('动画结束');
element.style.display = 'none';
});
性能优化建议
避免在动画中触发重排属性如width、height等,优先使用transform和opacity等合成层属性。使用will-change提示浏览器优化准备。
element.style.willChange = 'transform, opacity';






