如何使用JavaScript实现动画的依次连续执行?
解决方案
要实现小球从左上→右下→右上的连续移动,核心是用阶段标记区分不同的移动阶段,避免直接判断单一位置值导致的逻辑提前触发问题。
修改后的完整代码
HTML
<button onclick="animation()">Click Here</button> <div id="box"> <div id="ball"></div> </div>
CSS
#box { width: 400px; height: 400px; margin-top: 20px; position: relative; background: yellow; } #ball { width: 50px; height: 50px; position: absolute; background-color: red; border-radius: 100%; }
JavaScript
function animation() { let id = null; const ball = document.getElementById("ball"); let pos = 0; // 标记当前移动阶段:1=左上→右下,2=右下→右上 let stage = 1; id = setInterval(movement, 5); function movement() { if (stage === 1) { // 第一阶段:往右下移动,top和left同步递增 if (pos === 350) { // 到达右下,切换到第二阶段 stage = 2; ball.style.background = "orange"; } else { pos++; ball.style.top = pos + "px"; ball.style.left = pos + "px"; } } else if (stage === 2) { // 第二阶段:往右上移动,top递减,left保持350 if (pos === 0) { // 到达右上,停止动画 clearInterval(id); ball.style.background = "green"; } else { pos--; ball.style.top = pos + "px"; ball.style.left = "350px"; } } } }
关键说明
- 新增
stage变量区分移动阶段,彻底解决了直接判断pos==350时立刻执行后续逻辑的问题 - 第一阶段完成(pos=350)时,仅切换阶段标记、不清除定时器,保证动画连续无中断
- 第二阶段移动时,固定
left为350px,只调整top值递减,精准实现往右上角移动的效果 - 只有当第二阶段完全完成(pos=0)时,才清除定时器并修改小球颜色
内容的提问来源于stack exchange,提问作者kay
相关产品推荐
相关产品推荐

