我正在尝试编写一个程序来说明"Towers of Hanoi"拼图的程序化解决方案,其中磁盘由绝对定位的不同大小的div表示。为了采取行动,我有这样的功能:
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()没有任何可见效果。谷歌搜索显示使用动画回调的一些建议,但我不认为它们适用于我的情况。
答案 0 :(得分:7)
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/