坚持使用Jquery动画无限循环

时间:2016-02-21 03:04:19

标签: javascript jquery css

我正在尝试创建气泡,经过几次重复我的浏览器卡住了。这是我的代码。有人请帮忙....如何完成许多请求完成它。

看起来我的帖子主要是代码,但我为此Stackoverflow添加了足够的详细信息:)

谢谢!

Jquery的:

    $(document).ready(function() {

                           function bubbles()
                       {


                       var i = 0;


                      $(".circle").remove();



                       for(i = 0; i < 3; i ++ )

                       {

                             var CreateDiv =   document.createElement('div');

                      var AppendElem =  document.body.appendChild(CreateDiv);

                      AppendElem.setAttribute('class','circle');

                      CreateDiv.style.position = "absolute";

                      var randomPosTop = Math.floor((Math.random() * 800) + 1);

                      CreateDiv.style.top = randomPosTop +"px";

                       var randomPosLeft = Math.floor((Math.random() * 1200) + 1);

                       CreateDiv.style.left = randomPosLeft +"px";

                        }

                        $( ".circle" ).animate({ opacity :0.0,height:100, width:100 }, 5000,bubbles);


                       }

                       bubbles();


                       });

CSS

        .circle{ width: 20px;
                 height: 20px;
                 background-color: #000;
                 border-radius: 100px; position:absolute;}

的jsfiddle

     https://jsfiddle.net/krishnakamal549/u4krxq8o/

2 个答案:

答案 0 :(得分:2)

问题是动画中的回调会为它找到的每个元素调用。所以..第一次被调用3次,第二次被调用9次,第三次被调用18次,每次被调三次,最终你会运行数百个&#34;起泡&#34;的实例。

您希望使用承诺来执行回调,如此。

   $(".circle").animate({
     opacity: 0.0,
     height: 100,
     width: 100
   }, 5000).promise().done(bubbles);

这样,回调只会为整个动画触发一次,而不是每个元素。

FIDDLE

答案 1 :(得分:1)

// If player gets eaten by a monster: GAME OVER!
if (((player->x == monster->x)  && (player->y == monster->y)) ||
    ((player->x == monster2->x)  && (player->y == monster2->y)))
{
    printf("GAME OVER!\n");
    free_memory();
    // Now return from the function
    return;
}

试试这个,这也有效。 但我建议使用Smeegs指定的approach

此方法为动画的$(".circle").animate({ opacity: 0.0, height: 100, width: 100 }, 5000); $("body").animate({ opacity: 1 }, 5000, bubbles); 添加了额外的处理,而Smeegs的处理直接处理动画应用的位置,而不需要body上的额外动画处理