如何让CSS动画实现匀速运动?是否需使用JavaScript?
用少量JavaScript实现匀速移动动画
嘿,这个问题我太懂了!你遇到的是CSS动画默认的缓动特性——默认的animation-timing-function是ease,也就是动画会先缓慢加速、中间保持速度、最后减速收尾,所以才会出现开头和结尾变慢的情况。如果想用少量JavaScript实现全程恒定速度的移动,用requestAnimationFrame就能轻松搞定,代码简洁还灵活:
实现步骤
首先简化你的CSS,去掉自带的动画,只保留基础样式:
.MovingDiv { position: fixed; width: 50px; height: 50px; background-color: red; left: 0; /* 初始位置设为左侧 */ }
然后用JavaScript控制匀速移动:
const movingDiv = document.querySelector('.MovingDiv'); let currentPosition = 0; const targetPosition = 1000; // 目标位置(右侧1000px处) const speed = 200; // 移动速度:200像素/秒 function moveElement(timestamp) { // 计算当前帧与上一帧的时间差(转为秒) if (!moveElement.lastTimestamp) moveElement.lastTimestamp = timestamp; const deltaTime = (timestamp - moveElement.lastTimestamp) / 1000; // 根据时间差计算移动距离,保证速度恒定 currentPosition += speed * deltaTime; // 到达目标位置后停止动画 if (currentPosition >= targetPosition) { movingDiv.style.left = `${targetPosition}px`; return; } // 更新元素位置 movingDiv.style.left = `${currentPosition}px`; moveElement.lastTimestamp = timestamp; // 请求下一帧继续动画 requestAnimationFrame(moveElement); } // 启动动画 requestAnimationFrame(moveElement);
代码说明
requestAnimationFrame会同步浏览器的刷新频率,让动画更流畅,避免卡顿- 通过计算每帧的时间差(
deltaTime)来确定该帧的移动距离,不管浏览器帧率如何,元素的移动速度始终是你设定的200像素/秒 - 当元素到达目标位置后自动停止,不会做多余的计算
额外小提示
其实CSS里只需要修改一行代码也能实现匀速:把animation-timing-function设为linear就好,比如:
.MovingDiv { position: fixed; width: 50px; height: 50px; background-color: red; animation: MovingAnimation 5s linear; } @keyframes MovingAnimation { 0% {left: 0px;} 100% {left: 1000px;} }
不过既然你明确想要JavaScript实现的方案,上面的JS代码完全能满足需求,而且后续还能轻松扩展(比如添加暂停、调速功能)。
内容的提问来源于stack exchange,提问作者Clint Anumudu
相关产品推荐
相关产品推荐

