用js实现动画
使用 CSS 和 JavaScript 实现动画
在 JavaScript 中实现动画可以通过多种方式完成,包括使用 CSS 动画、JavaScript 原生动画方法或第三方库(如 GSAP)。以下是几种常见的实现方法。
使用 CSS 动画和 JavaScript 控制
CSS 动画性能较好,适合简单的过渡效果。可以通过 JavaScript 动态添加或移除 CSS 类来触发动画。

<style>
.box {
width: 100px;
height: 100px;
background-color: red;
transition: transform 1s ease;
}
.box.animate {
transform: translateX(200px);
}
</style>
<div class="box"></div>
<button onclick="startAnimation()">开始动画</button>
<script>
function startAnimation() {
const box = document.querySelector('.box');
box.classList.add('animate');
}
</script>
使用 JavaScript 原生 requestAnimationFrame
requestAnimationFrame 是浏览器提供的 API,适合实现复杂的逐帧动画。

<div id="box" style="width: 100px; height: 100px; background-color: blue; position: absolute;"></div>
<button onclick="startAnimation()">开始动画</button>
<script>
function startAnimation() {
const box = document.getElementById('box');
let position = 0;
function animate() {
position += 2;
box.style.left = position + 'px';
if (position < 200) {
requestAnimationFrame(animate);
}
}
animate();
}
</script>
使用 Web Animations API
Web Animations API 是浏览器原生支持的动画 API,结合了 CSS 动画的性能和 JavaScript 的灵活性。
<div id="box" style="width: 100px; height: 100px; background-color: green;"></div>
<button onclick="startAnimation()">开始动画</button>
<script>
function startAnimation() {
const box = document.getElementById('box');
box.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
], {
duration: 1000,
easing: 'ease-in-out'
});
}
</script>
使用第三方库 GSAP
GSAP(GreenSock Animation Platform)是一个强大的动画库,适合复杂的动画需求。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<div id="box" style="width: 100px; height: 100px; background-color: purple;"></div>
<button onclick="startAnimation()">开始动画</button>
<script>
function startAnimation() {
gsap.to("#box", {
x: 200,
duration: 1,
ease: "power2.inOut"
});
}
</script>
性能优化建议
- 优先使用 CSS 动画或 Web Animations API,因为它们可以利用浏览器的硬件加速。
- 避免频繁操作 DOM,尤其是在逐帧动画中。
- 使用
transform和opacity属性进行动画,这些属性不会触发重排(reflow)。 - 对于复杂的动画序列,考虑使用 GSAP 等库,它们提供了更好的性能和兼容性。
以上方法可以根据具体需求选择,CSS 动画适合简单过渡,JavaScript 原生方法适合自定义动画,而 GSAP 适合复杂的动画场景。






