JavaScript 实现动画效果主要依赖于以下几个基础概念和技术:
setTimeout
或 setInterval
这是最基本的实现动画的方法,通过定时器不断改变元素的样式属性。
function animate(element, target, duration) {
let start = null;
const initial = parseFloat(getComputedStyle(element)[target]);
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const percentage = Math.min(progress / duration, 1);
element.style[target] = initial + (target === 'opacity' ? percentage : percentage * 100) + '%';
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
// 使用示例
const box = document.getElementById('box');
animate(box, 'left', 2000); // 将元素向左移动2000px
CSS3 提供了 transition
和 animation
属性,可以很方便地实现复杂的动画效果。
/* CSS */
#box {
width: 100px;
height: 100px;
background-color: red;
transition: left 2s;
}
// JavaScript
document.getElementById('box').style.left = '200px';
requestAnimationFrame
这是一个优化的动画循环,它会在浏览器准备重绘下一帧时调用提供的回调函数,通常比 setTimeout
或 setInterval
更高效。
function animate() {
// 更新动画状态
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
requestAnimationFrame
可以确保动画在最佳时机执行,减少资源消耗。requestAnimationFrame
替代 setTimeout/setInterval
,优化 JavaScript 执行效率。通过上述方法和技巧,可以有效地在网页中实现各种动画效果,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云