jQuery动画执行顺序问题:animate未完成css提前执行及动画实现
根本原因
- jQuery的
animate()方法为异步设计,调用后会立即返回,不会阻塞后续代码的同步执行 - 仅jQuery动画类方法会默认加入内置动画队列按顺序执行,
css()方法不属于动画队列,会立即执行,因此第一个动画还在运行时,修改背景为蓝色的代码就已经生效 - 额外注意:你的代码中存在拼写错误,首次设置背景色时将
background错写为backgound,会导致初始红色无法正常生效
修复方案
将修改背景色的逻辑放入第一个animate()的回调函数中,回调函数会在当前动画完全执行完成后触发,即可保证水平移动阶段背景为红色,移动结束后变为蓝色再执行后续向下移动的动画。
修正后代码如下:
$(document).ready( function() { // start box animation code let animatedBox = $('.box'); // 修复拼写错误 animatedBox.css('background', 'red'); animatedBox.animate( { left: '500px', height: '250px', width: '250px' }, 1000, function() { // 第一个动画执行完成后再修改背景色 animatedBox.css('background', 'blue'); }); // 动画方法会自动加入队列,等待前一个动画完成后执行 animatedBox.animate( { top: '500px', height: '100px', width: '100px' }, 1000); // end box animation code });
内容的提问来源于stack exchange,提问作者noorblue
相关产品推荐
相关产品推荐

