【问题标题】:jQuery animation order without callbacks没有回调的jQuery动画顺序
【发布时间】:2011-07-28 12:14:35
【问题描述】:

我正在尝试编写一个程序来说明"Towers of Hanoi" 难题的编程解决方案,其中磁盘由不同大小的绝对定位的 div-s 表示。为了采取行动,我有这样的功能:

function move(peg_from, peg_to)
{
//check if the move is valid
//update the game state
//......
//get the div we are moving, calculate it's new position
//move:
the_div.animate({left: new_left, top: new_top}, 500);
}

那么解决方案可能如下所示:

move(1, 3);
move(1, 2);
move(3, 2);
//... etc...

或递归,或其他。无论如何,我希望能够“评估”任何代码,这些代码是根据 move(x, y) 定义的,而不是根据 jQuery 的动画或回调函数定义的。问题是,所有动画同时发生,而它需要按调用顺序进行。有没有办法做到这一点?

我尝试将 .delay() 添加到动画中,也许它可以工作,但无论如何我无法确定正确的超时时间。 setTimeout() 没有任何可见的效果。谷歌搜索揭示了一些使用动画回调的建议,但我认为它们不适用于我的情况。

【问题讨论】:

  • 用工作游戏更新答案(manual

标签: jquery


【解决方案1】:

A non-nested animation sequence in jQuery? 的答案也符合您的问题(稍作修改)..

你需要.queue()你的动画..

var q = $({});

function moveToQueue(eg_from, peg_to) {
    q.queue(function(next) {
        //check if the move is valid
        //update the game state
        //......
        //get the div we are moving, calculate it's new position
        //move:
        the_div.animate({left: new_left, top: new_top}, 500, next);
    });
}


// usage
moveToQueue(1, 3);
moveToQueue(1, 2);
moveToQueue(3, 2);

更新

因为我喜欢它..
这是一个完整的工作解决方案.. http://jsfiddle.net/gaby/nZ4MU/

【讨论】:

  • 顺便说一句,将所有游戏逻辑移到function(next){}之外不是更好吗,例如。 G。只在大括号内留下 the_div.animate(...);并将其他所有内容上移一层?特别是因为对 moveToQueue 的调用不一定会添加动画(移动可能无效)。
  • @headcrab 是的,您可以将这些问题分开,仅在移动通过所有检查时处理动画
  • 我不得不说我很喜欢看动画。 +1 以确保解决方案的完整性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多