jQuery animate loop

2019-01-19 03:27发布

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.

2条回答
叼着烟拽天下
2楼-- · 2019-01-19 04:13

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.

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

   runIt();
});
查看更多
甜甜的少女心
3楼-- · 2019-01-19 04:17

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.callee as the callback

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 fiddle a 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.

查看更多
登录 后发表回答