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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…