当完成函数或回调嵌套太深或代码一遍又一遍地重复时,我倾向于考虑具有通用函数的数据表解决方案:
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);
而且,如果您希望某些项目具有不同类型的动画,您可以创建一个对象数组来描述每个连续动画应该是什么。您可以根据需要在对象数组中添加尽可能多的细节。您甚至可以将动画与其他同步 jQuery 方法调用混合,如下所示:
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);
而且,这是第二个选项的工作演示:http: //jsfiddle.net/jfriend00/PEVEh/