用js实现css动画
使用JavaScript实现CSS动画
JavaScript可以通过直接操作DOM元素的样式或使用requestAnimationFrame实现高性能动画。以下是几种常见方法:
通过修改style属性实现基础动画
const element = document.getElementById('target');
let position = 0;
function animate() {
position += 1;
element.style.transform = `translateX(${position}px)`;
if (position < 100) {
requestAnimationFrame(animate);
}
}
animate();
使用classList切换CSS类
/* CSS定义 */
.animate {
transition: transform 0.5s ease-out;
transform: translateX(100px);
}
const element = document.getElementById('target');
element.classList.add('animate');
高性能requestAnimationFrame实现
function smoothAnimation(element, duration, distance) {
const startTime = performance.now();
function update(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const position = progress * distance;
element.style.transform = `translateX(${position}px)`;
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
Web Animations API(现代浏览器支持)
const element = document.getElementById('target');
element.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(100px)' }
], {
duration: 500,
easing: 'ease-out'
});
结合CSS变量实现动态控制
/* CSS定义 */
.element {
--x-pos: 0;
transition: transform 0.3s;
transform: translateX(var(--x-pos));
}
const element = document.getElementById('target');
element.style.setProperty('--x-pos', '100px');
性能优化建议
- 优先使用CSS硬件加速属性(transform/opacity)
- 避免在动画过程中触发重排(如读取offsetHeight)
- 对大量元素动画考虑使用WebGL或Canvas方案
- 使用
will-change属性提前告知浏览器变化属性
浏览器兼容处理
对于旧版浏览器需要添加polyfill:

// requestAnimationFrame的polyfill
window.requestAnimationFrame = window.requestAnimationFrame ||
function(callback) {
return setTimeout(callback, 1000/60);
};
这些方法可以根据具体场景选择使用,CSS动画适合简单过渡效果,JavaScript动画适合需要复杂逻辑控制的场景。






