【问题标题】:Javascript-Jquery - animate method inside for loopJavascript-Jquery - for 循环内的动画方法
【发布时间】:2016-01-28 13:22:36
【问题描述】:

我有下面的循环,从 1 计数到 100。

我想在这个循环中使用 animate 方法来平滑地移动图片,即通过改变它的顶部和左侧属性。

虽然我可以让图片移动,但它是在一个生涩的动画中完成的。我可能有点笨,但它似乎是一次性执行所有动画而不是逐步执行。

这与 javascript 是异步的有关吗?

还有一种方法可以让我在 Javascript 中重复某些内容,即不是设置循环,而是有一种方法可以让函数在最后调用自己,例如,我可以显示动画 div不断反弹等。目前我必须设置一个预定义的循环。

for (i=1; i < 100; i++) {
    var FirstTop = (FirstTop + FirstTopGoal);
    var FirstLeft= (FirstLeft+ (FirstLeftGoal));
    var SecondTop = (SecondTop+ (SecondTopGoal));
    var SecondLeft = (SecondLeft + (SecondLeftGoal));
    if (FirstTop<100){Firsttop=100;FirstTopGoal    = 2 - Math.random()*4;};
    if (FirstLeft<50){FirstLeft=50;FirstLeftGoal    = 2 - Math.random()*4;};
    if (FirstTop>130){Firsttop=130;FirstTopGoal    = 2 - Math.random()*4;};
    if (FirstLeft>500){Firsttop=500;FirstLeftGoal    = 2 - Math.random()*4;};
    $("#first").animate(
        {top: FirstTop,left:FirstLeft},
        {duration: 0,
        easing: "linear"}
    );
};

【问题讨论】:

  • 您将动画持续时间设置为 0,所以我不知道您为什么希望它显示流畅的动画。

标签: jquery loops jquery-animate


【解决方案1】:

这段代码应该可以解决你的问题:

var i = 1;
var interval = setInterval(function(){
    if(i < 100) {
        i++;

        var FirstTop = (FirstTop + FirstTopGoal);
        var FirstLeft= (FirstLeft+ (FirstLeftGoal));
        var SecondTop = (SecondTop+ (SecondTopGoal));
        var SecondLeft = (SecondLeft + (SecondLeftGoal));
        if (FirstTop<100){Firsttop=100;FirstTopGoal    = 2 - Math.random()*4;};
        if (FirstLeft<50){FirstLeft=50;FirstLeftGoal    = 2 - Math.random()*4;};
        if (FirstTop>130){Firsttop=130;FirstTopGoal    = 2 - Math.random()*4;};
        if (FirstLeft>500){Firsttop=500;FirstLeftGoal    = 2 - Math.random()*4;};

        $("#first").animate(
            { top: FirstTop, left:FirstLeft}, 
            {duration: 0, easing: "linear"}
        );
    }
    else if(i == 100){
        clearInterval(interval);
    }
}, 1);

使用setInterval 而不是for 循环,因为。 Here你可以在jsFiddle上看到一个例子。

for 循环比setInterval 更快,如果您指定延迟为 0。这是因为setInterval 的最小延迟值为 4 毫秒。 也看看这个问题:Why setTimeout(function, 0) is executed after next operation, but not in the moment of calling?

【讨论】:

  • jQuery 动画会自动放入队列中,因此信号量基本上什么都不做。
  • @Juhana 你说得对!对不起,我忘记了这个特殊性。我将更新我的代码删除信号量。
猜你喜欢
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多