Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
147 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...