动画js怎么实现
使用CSS动画结合JavaScript
CSS动画通过@keyframes定义动画效果,JavaScript用于触发或控制动画。例如,点击按钮触发元素旋转:
/* CSS */
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spin-animation {
animation: spin 2s linear infinite;
}
// JavaScript
document.getElementById('trigger').addEventListener('click', () => {
document.getElementById('box').classList.add('spin-animation');
});
纯JavaScript实现动画
通过requestAnimationFrame逐帧修改样式,实现平滑动画效果。以下代码让元素水平移动:
function animate(element, duration) {
const start = performance.now();
const distance = 200; // 移动距离
function step(timestamp) {
const elapsed = timestamp - start;
const progress = Math.min(elapsed / duration, 1);
element.style.transform = `translateX(${progress * distance}px)`;
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
animate(document.getElementById('box'), 1000);
使用Web Animations API
现代浏览器原生支持的API,可直接用JavaScript定义关键帧和动画参数:
const element = document.getElementById('box');
element.animate([
{ opacity: 0, transform: 'scale(0.5)' },
{ opacity: 1, transform: 'scale(1.2)' },
{ opacity: 0.8, transform: 'scale(1)' }
], {
duration: 1000,
easing: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
iterations: Infinity
});
使用GSAP等动画库
GSAP提供更强大的时间轴控制和复杂动画序列:
gsap.to(".box", {
x: 100,
rotation: 360,
duration: 2,
ease: "bounce.out"
});
// 时间轴动画
const tl = gsap.timeline();
tl.to(".box1", { x: 200, duration: 1 })
.to(".box2", { y: 100, duration: 0.5 }, "-=0.5");
实现交互动画
结合用户交互事件实现响应式动画,如鼠标跟随效果:
document.addEventListener('mousemove', (e) => {
const x = e.clientX / window.innerWidth * 100;
const y = e.clientY / window.innerHeight * 100;
document.documentElement.style.setProperty('--cursor-x', `${x}%`);
document.documentElement.style.setProperty('--cursor-y', `${y}%`);
});
:root {
--cursor-x: 50%;
--cursor-y: 50%;
}
.follower {
position: absolute;
left: var(--cursor-x);
top: var(--cursor-y);
transition: transform 0.1s ease-out;
}
性能优化建议
优先使用CSS硬件加速属性如transform和opacity,避免频繁触发重排。使用will-change提示浏览器优化:
.animated-element {
will-change: transform, opacity;
}
对于复杂场景,考虑使用Web Workers处理计算密集型动画逻辑,主线程仅负责渲染。







