js实现div动画
使用 CSS Transition 实现简单动画
通过 CSS transition 属性结合 JavaScript 动态修改样式,实现平滑过渡效果。
HTML
<div id="box"></div>
<button onclick="moveBox()">移动</button>
CSS
#box {
width: 100px;
height: 100px;
background-color: red;
transition: all 0.5s ease;
}
JavaScript
function moveBox() {
const box = document.getElementById("box");
box.style.transform = "translateX(200px)";
}
使用 CSS Animation 实现关键帧动画
通过 JavaScript 动态添加或移除 CSS 动画类。
CSS

@keyframes slide {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
.animate {
animation: slide 1s forwards;
}
JavaScript
function startAnimation() {
const box = document.getElementById("box");
box.classList.add("animate");
}
使用 requestAnimationFrame 实现高性能动画
适用于需要精细控制的复杂动画。
JavaScript
let position = 0;
function animate() {
const box = document.getElementById("box");
position += 2;
box.style.transform = `translateX(${position}px)`;
if (position < 200) {
requestAnimationFrame(animate);
}
}
使用 GSAP 库实现高级动画
GSAP 提供更强大的动画控制,适合复杂场景。

引入 GSAP
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
JavaScript
gsap.to("#box", {
x: 200,
duration: 1,
rotation: 360,
ease: "bounce.out"
});
使用 Web Animations API
现代浏览器原生支持的动画 API,无需额外库。
JavaScript
const box = document.getElementById("box");
box.animate(
[
{ transform: "translateX(0)" },
{ transform: "translateX(200px)" }
],
{
duration: 1000,
easing: "ease-in-out"
}
);






