gdy kiedykolwiek funkcje zakończeniu lub callbacks się zagnieżdżone zbyt głęboko lub kod jest uzyskiwanie powtarzane w kółko, I mają tendencję do myślenia o rozwiązaniu z tablicą danych o wspólnej funkcji:
function fadeSequence(list) {
var index = 0;
function next() {
if (index < list.length) {
$(list[index++]).fadeOut(next);
}
next();
}
var fades = ["div1", "div2", "div3", "div4", "div5"];
fadeSequence(fades);
Jeśli chcesz uzyskać inny typ animacji dla niektórych elementów, możesz utworzyć tablicę obiektów opisujących, czym powinna być każda kolejna animacja. Możesz umieścić tyle szczegółów w tablicy obiektów, ile potrzeba. Można nawet INTERMIX animacje z drugiej synchronicznej metody jQuery zwraca tak:
function runSequence(list) {
var index = 0;
function next() {
var item, obj, args;
if (index < list.length) {
item = list[index++];
obj = $(item.sel);
args = item.args.slice(0);
if (item.sync) {
obj[item.type].apply(obj, args);
setTimeout(next, 1);
} else {
args.push(next);
obj[item.type].apply(obj, args);
}
}
}
next();
}
// sequence of animation commands to run, one after the other
var commands = [
{sel: "#div2", type: "animate", args: [{ width: 300}, 1000]},
{sel: "#div2", type: "animate", args: [{ width: 25}, 1000]},
{sel: "#div2", type: "fadeOut", args: ["slow"]},
{sel: "#div3", type: "animate", args: [{ height: 300}, 1000]},
{sel: "#div3", type: "animate", args: [{ height: 25}, 1000]},
{sel: "#div3", type: "fadeOut", args: ["slow"]},
{sel: "#div4", type: "fadeOut", args: ["slow"]},
{sel: "#div1", type: "fadeOut", args: ["slow"]},
{sel: "#div5", type: "css", args: ["position", "absolute"], sync: true},
{sel: "#div5", type: "animate", args: [{ top: 500}, 1000]}
];
runSequence(commands);
A oto demo działa od tej drugiej opcji: http://jsfiddle.net/jfriend00/PEVEh/
http://cdmckay.org/blog/2010/06/22/how-to-use-custom-jquery-animation-queues/ – Brad