如何正确插入回调函数,使一个函数结束,然后执行另一个函数

How to insert a callback function correctly so as to let one function end and then execute another

本文关键字:函数 结束 一个 执行 然后 另一个 插入 何正确 回调      更新时间:2023-09-26

我有这个简单的滑块JScript,根据您单击的按钮将缩略图悬停在左侧或右侧。

<script>
$(document).ready(function()
{
$(".right-arrow").click(function(){
$(".box1").animate({right:"1100px"},800);
$(".box2").animate({right:"1100px"},1000);
$(".box3").animate({right:"1100px"},1200);
$(".box4").animate({right:"1100px"},1400);
$(".box5").animate({right:"1100px"},1600);
$(".box6").animate({right:"1100px"},1800);
$(".box7").animate({right:"1100px"},2000);
$(".box8").animate({right:"1100px"},2200);
$(".box9").animate({right:"1100px"},2400);
$(".box10").animate({right:"1100px"},2600);
$(".box11").animate({right:"1100px"},2800);
$(".box12").animate({right:"1100px"},3000);
});
$(".left-arrow").click(function(){

$(".box12").animate({right:"0px"},800);
$(".box11").animate({right:"0px"},1000);
$(".box10").animate({right:"0px"},1200);
$(".box9").animate({right:"0px"},1400);
$(".box8").animate({right:"0px"},1600);
$(".box7").animate({right:"0px"},1800);
$(".box6").animate({right:"0px"},2000);
$(".box5").animate({right:"0px"},2200);
$(".box4").animate({right:"0px"},2400);
$(".box3").animate({right:"0px"},2600);
$(".box2").animate({right:"0px"},2800);
$(".box1").animate({right:"0px"},3000);
});
});
</script>

然而,如果我点击右键,然后快速点击左键,我得到一个拥挤的缩略图"碰撞"与另一个。

我如何插入一个很好的回调函数,以便等待一侧的动画完成,然后以另一种方式进行?

首先,当您在代码中看到模式时,这是一个很好的指示,您应该开始重构:

$(document).ready(function() {
    $(".right-arrow").click(function(){
        for (i = 1; i < 13; i++){
            $('.box' + i).stop().animate({
                right: 1000
            }, {
                duration: 600 + (i * 200), 
                queue: true
            });
        }
    });
    $(".left-arrow").click(function(){
        for (i = 1; i < 13; i++){
            $('.box' + i).stop().animate({
                right: 0
            }, {
                duration: 3200 - (i * 200),
                queue: true
            });
        }
    });
}

关于时间冲突,您所需要的只是传递true作为队列选项,这将确保后续动画在前一个动画完成后开始。

看看这里的JQuery Animate

var domArray = [$(".box1"), $(".box2"), $(".box3")....];
var runningIndex = 0;
function runAnimate(){
  domArray[runningIndex].animate({right:"0px"},800 + runningIndex*200, function(){
    if(domArray.length > runningIndex){
      runningIndex ++;
      runAnimate();
    }
  });
}
$(".right-arrow").click(function(){
  runningIndex = 0;
  runAnimate();
});