js实现动画效果代码
使用 CSS 和 JavaScript 实现基础动画
通过修改元素的 style 属性实现简单动画效果。以下代码使一个方块水平移动:

const box = document.getElementById('box');
let position = 0;
function animate() {
position += 2;
box.style.left = position + 'px';
if (position < 200) {
requestAnimationFrame(animate);
}
}
animate();
使用 CSS 类切换实现动画
定义 CSS 动画关键帧,通过 JavaScript 切换类名触发:

@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
.box {
width: 100px;
height: 100px;
background: blue;
}
.box.animate {
animation: slide 2s forwards;
}
document.getElementById('box').classList.add('animate');
使用 Web Animations API
现代浏览器支持的动画 API,提供更精细的控制:
const box = document.getElementById('box');
box.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
], {
duration: 1000,
iterations: Infinity,
direction: 'alternate'
});
使用第三方动画库(GSAP)
GSAP 提供强大的动画控制能力:
gsap.to("#box", {
x: 200,
duration: 1,
repeat: -1,
yoyo: true
});
性能优化建议
优先使用 CSS 动画处理简单效果,复杂交互使用 JavaScript 动画。避免频繁触发重排的属性如 width/height,改用 transform 和 opacity 这类合成层属性。使用 requestAnimationFrame 替代 setTimeout 保证动画流畅性。






