js 实现动画
使用 CSS 和 JavaScript 实现动画
在 JavaScript 中实现动画可以通过多种方式,包括 CSS 动画、requestAnimationFrame 以及第三方库(如 GSAP)。以下是几种常见的方法:
CSS 动画结合 JavaScript
通过 CSS 定义动画,然后使用 JavaScript 控制动画的触发或修改属性。
/* CSS 定义动画 */
.box {
width: 100px;
height: 100px;
background: red;
transition: transform 1s ease;
}
.box.animate {
transform: translateX(200px);
}
// JavaScript 触发动画
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.classList.add('animate');
});
使用 requestAnimationFrame
requestAnimationFrame 是浏览器提供的原生 API,适合实现高性能的 JavaScript 动画。
const box = document.querySelector('.box');
let position = 0;
function animate() {
position += 2;
box.style.transform = `translateX(${position}px)`;
if (position < 200) {
requestAnimationFrame(animate);
}
}
animate();
使用 setInterval 或 setTimeout
虽然 setInterval 和 setTimeout 可以实现动画,但性能不如 requestAnimationFrame。
const box = document.querySelector('.box');
let position = 0;
const animation = setInterval(() => {
position += 2;
box.style.transform = `translateX(${position}px)`;
if (position >= 200) {
clearInterval(animation);
}
}, 16);
使用 GSAP(GreenSock Animation Platform)
GSAP 是一个强大的动画库,适合复杂的动画场景。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
const box = document.querySelector('.box');
gsap.to(box, { x: 200, duration: 1, ease: "power2.out" });
使用 Web Animations API
Web Animations API 是浏览器原生支持的动画 API,可以直接操作 CSS 动画。

const box = document.querySelector('.box');
box.animate(
[
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
],
{
duration: 1000,
easing: 'ease-in-out'
}
);
性能优化建议
- 优先使用
requestAnimationFrame或 CSS 动画,避免使用setInterval。 - 使用
transform和opacity属性实现动画,这些属性不会触发重排(reflow)。 - 对于复杂动画,考虑使用 GSAP 或 Web Animations API。
以上方法可以根据具体需求选择,CSS 动画适合简单效果,而 JavaScript 动画适合需要动态控制的场景。






