如何用JavaScript实现盒子平滑缓慢移动至bottom:0、right:0的指定位置?
解决红色盒子平滑移动到右下角的问题
原代码的问题点
var x = bottom、var y = right是错误写法,bottom和right不是定义好的变量,且你要操作的是元素的bottom和right样式属性setInterval的回调函数是空的,后面的位置更新代码不在定时器内,只会执行一次,无法形成连续动画- 目标是移动到右下角(bottom:0、right:0),但原代码在修改
top和left,方向完全相反
方案1:用CSS Transition(最简单,适合新手)
直接通过CSS添加过渡效果,修改元素的bottom和right属性即可实现平滑动画,JS只需要触发样式变化:
<html> <div id="my_box_realtime" style="background-color: red; position: absolute; min-width: 100px; min-height: 100px; transition: all 1s ease;"></div> <script type="text/javascript"> const box = document.getElementById('my_box_realtime'); // 直接设置目标位置,CSS过渡会自动处理平滑动画 box.style.bottom = '0px'; box.style.right = '0px'; </script> </html>
transition: all 1s ease:表示所有样式变化都会在1秒内以缓动效果完成,你可以调整1s改成更慢的速度(比如3s),ease可以换成linear(匀速)等过渡函数
方案2:用JavaScript requestAnimationFrame(更灵活可控)
如果需要更精细控制动画过程(比如调整每帧移动距离),可以用浏览器原生的requestAnimationFrame,它比setInterval更适合动画:
<html> <div id="my_box_realtime" style="background-color: red; position: absolute; min-width: 100px; min-height: 100px;"></div> <script type="text/javascript"> const box = document.getElementById('my_box_realtime'); // 初始位置:假设一开始在top:0、left:0 let currentBottom = window.innerHeight - box.offsetHeight; // 初始bottom值(从顶部到盒子底部的距离) let currentRight = window.innerWidth - box.offsetWidth; // 初始right值(从左侧到盒子右侧的距离) const step = 2; // 每帧移动的像素数,越小越慢越平滑 function animate() { // 逐步减少bottom和right的值,直到达到0 if (currentBottom > 0) { currentBottom = Math.max(0, currentBottom - step); box.style.bottom = currentBottom + 'px'; } if (currentRight > 0) { currentRight = Math.max(0, currentRight - step); box.style.right = currentRight + 'px'; } // 只要还没到目标位置,继续下一帧动画 if (currentBottom > 0 || currentRight > 0) { requestAnimationFrame(animate); } } // 启动动画 animate(); </script> </html>
requestAnimationFrame会根据浏览器的刷新率自动调整帧速率,动画更流畅step变量控制移动速度,数值越小移动越慢
内容的提问来源于stack exchange,提问作者Lcgress
相关产品推荐
相关产品推荐

