JavaScript 实现左右移动动画效果通常涉及以下几个基础概念:
setInterval
或 requestAnimationFrame
,用于周期性地更新元素的位置。requestAnimationFrame
是优化动画效果的 API,它会在浏览器重绘之前调用指定的回调函数。<div id="movingBox" style="width: 50px; height: 50px; background-color: red; position: absolute;"></div>
#movingBox {
left: 0;
}
const box = document.getElementById('movingBox');
let start = null;
const duration = 2000; // 动画持续时间,单位毫秒
const distance = 200; // 移动的距离,单位像素
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const percentage = Math.min(progress / duration, 1);
const newPosition = distance * percentage;
box.style.left = `${newPosition}px`;
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
requestAnimationFrame
可以确保动画在每一帧都得到更新,从而实现更流畅的效果。requestAnimationFrame
而不是 setInterval
。position: absolute;
)。通过以上步骤和技巧,可以有效地创建出平滑且性能良好的左右移动动画效果。
领取专属 10元无门槛券
手把手带您无忧上云