Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - jQuery animate loop

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...