js实现动画移动
使用CSS动画实现简单移动
通过@keyframes定义动画,结合transform属性实现位移效果:
.box {
width: 100px;
height: 100px;
background: red;
animation: move 2s infinite alternate;
}
@keyframes move {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
使用requestAnimationFrame实现控制
通过JavaScript精确控制每一帧的动画状态:
const element = document.querySelector('.box');
let position = 0;
let speed = 2;
function animate() {
position += speed;
element.style.transform = `translateX(${position}px)`;
if (position < 200) {
requestAnimationFrame(animate);
}
}
animate();
使用GSAP动画库
引入GSAP库实现专业级动画效果:
gsap.to(".box", {
x: 200,
duration: 2,
repeat: -1,
yoyo: true,
ease: "power1.inOut"
});
Web Animations API实现
使用浏览器原生动画API:
const element = document.querySelector('.box');
element.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
], {
duration: 1000,
iterations: Infinity,
direction: 'alternate'
});
使用CSS transition实现交互动画
通过类名切换触发过渡效果:
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.classList.toggle('moved');
});
配合CSS:
.box {
transition: transform 0.5s ease;
}
.box.moved {
transform: translateX(200px);
}






