抽搐效果动画移动物体

时间:2014-06-25 11:02:36

标签: jquery jquery-animate

我有一个在给定范围内从左到右不断移动的盒子。我也有左右控制移动的盒子。我的问题是这样,我怎样才能使动画更流畅。目前,当它向右侧动画时,你单击左控件,它会变得生涩或跳跃。我创建了一个jsfiddle链接here

$(".nav .left").click(function(){
            $("#boss").animate({
                left: "-=50"
            });     
            return false;
        });


        $(".nav .right").click(function(){
            $("#boss").animate({
                left: "+=50"
            });     
            return false;
        });



        function animateBoss() {
            var top   = randomMinMax(0 , 0);
            var left  = randomMinMax(0   , 400);    
            var speed = randomMinMax(1000, 1000);


            boss.animate({ top: top, left: left }, {
                duration: speed,
                queue   : false,
                complete: animateBoss
            });
        }    `enter code here`


        animateBoss();

2 个答案:

答案 0 :(得分:1)

我认为“生涩”的动作是由两个相互冲突的动画引起的:由animateBoss()触发并由点击“左”或“右”触发。

通过在手动“左”/“右”移动之前停止动画并在完成此类动作时重新启动animateBoss(),我取得了成功:

我正在使用jQuery的stop()来停止动画:

语法:.stop( [clearQueue ] [, jumpToEnd ] )

$(".nav .right").click(function(){
    $("#boss").stop(true,false).animate({
        left: "+=50"
    },function() {
        animateBoss();
    });
    return false;
});

Working Example

答案 1 :(得分:0)

使用jQuery动画时,如果您运行的动画超过1个动画或重复相同的动画,则应在动画前加dequeue()stop(),否则它们可能会在彼此后面等待运行并产生结果无意中延迟。

$("#boss").dequeue().stop().animate({ left: "-=50" });  

Here's a full Codepen demo