Javascript jQuery 动画循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6344544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:20:23  来源:igfitidea点击:

jQuery animate loop

javascriptjqueryanimation

提问by Anton

I have a problem with animate loop. There is an object i want to move in a special way and do it in loop. Are there any native options to make it? I have this:

我有动画循环问题。有一个对象我想以一种特殊的方式移动并循环进行。是否有任何本机选项可以实现?我有这个:

$(function () {
    function runIt() {
        $('#div').show("slow");
        $('#div').animate({"marginLeft":"300px"},8000);
        $('#div').animate({"marginLeft":"0px"},8000);
        $('#div').hide("slow", runIt);
    }
    runIt();
});

But it seems not so pretty.

不过好像没那么好看。

回答by mekwall

That's the proper way to queue animations. However, there's some things that can be made to your code to make it a bit snappier and prettier:

这是对动画进行排队的正确方法。但是,可以对您的代码进行一些操作,使其更快速、更漂亮:

  • Store a reference to the selected element in a local variable to speed up execution (less queries made to the DOM)
  • Clean it up by removing unnecessary quotes for object properties
  • Sizing is measured in pixels per default so we can use pure integers instead
  • The named function can be replaced with a immediately invoked anonymous function and then use arguments.calleeas the callback
  • 将所选元素的引用存储在局部变量中以加快执行速度(减少对 DOM 的查询)
  • 通过删除对象属性不必要的引号来清理它
  • 默认情况下,大小以像素为单位测量,因此我们可以使用纯整数代替
  • 命名函数可以替换为立即调用的匿名函数,然后arguments.callee用作回调

Here's an example showcasing the above changes:

以下是展示上述更改的示例:

$(function () {
    var element = $("#div");
    (function(){
        element
            .show("slow")
            .animate({ marginLeft: 300 }, 1000)
            .animate({ marginLeft: 0 },   1000)
            .hide("slow", arguments.callee);
    }());
});

You can also do it in a more advanced way by creating your own plugin to use custom queues. I created a small fiddlea while back when I was fooling around with animation queues.

您还可以通过创建自己的插件来使用自定义队列,以更高级的方式完成此操作。不久前,我在玩弄动画队列时创建了一个小小提琴

More about immediately invoked function expression can be read on Ben "Cowboy" Alman's blog.

有关立即调用函数表达式的更多信息,请参阅Ben “Cowboy” Alman 的博客

回答by James Montagne

That is how I would do it. The only suggestion I would make is to use chaining for nicer code and so the jquery object doesn't get created every time.

这就是我要做的。我会提出的唯一建议是使用链接以获得更好的代码,因此不会每次都创建 jquery 对象。

$(function () {
   function runIt() {
      $('#div').show("slow")
               .animate({"marginLeft":"300px"},8000)
               .animate({"marginLeft":"0px"},8000)
               .hide("slow", runIt);
   }

   runIt();
});