1

画面上を移動するためのいくつかのボックスを含む簡単な例があります。各ボックスは、前のボックスが完了するまで移動しないでください。を使用した実用的なソリューション.shift()がありますが、forループとを使用してこれを繰り返すことができるはず$.eachです。誰もがのためにそして$.each働く方法を知っていますか?

ここをいじると、Shiftボタンは私が望むように機能します。

ありがとう。

JS:

boxes = [
  ['.box0', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box1', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box2', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box3', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box4', 'animate', [ {left: '200px' }, 1000 ] ],
  ['div', 'animate', [ {left: '0px' }, 1000 ] ]
];
$('.eachMethod').click(animEach);
$('.ifMethod').click(animFor);
$('.shiftMethod').click(animShift);
function animEach(){
  $.each(boxes, function(){
    $.fn[this[1]].apply($(this[0]), this[2]).promise().done();
  });
};
function animFor(){
  for (i=0; i < boxes.length; i++) {
    b=boxes[i];
    $.fn[b[1]].apply($(b[0]), b[2]).promise().done();
  }
};
function animShift(){
  b = boxes.shift();
  if (b) {
    $.fn[b[1]].apply($(b[0]), b[2]).promise().done(animShift);
  }
};​

HTML:

<ul>
  <li><button class='eachMethod'>$.each</button></li>
  <li><button class='ifMethod'>if</button></li>
  <li><button class='shiftMethod'>shift</button></li>
</ul>
<div class='box0'></div>
<div class='box1'></div>
<div class='box2'></div>
<div class='box3'></div>
<div class='box4'></div>​

CSS:

div{
 clear: both;   
 background-color: green;
 width: 40px;
 height: 40px;
 Position: relative;    
}
ul li {
  float: left;
}
4

1 に答える 1

1

animate()は非同期であるため、ループは数ミリ秒で完了し、各要素のアニメーションを実質的に同時に呼び出します。.promise().done()ループを使用するときは何もしていません。

使用しているバージョンanimShift()は、一度に1つの要素にのみアニメーションを適用し、次の呼び出しが含まれdone()ているため、最初のアニメーションが完了するまで起動しません。

于 2012-11-25T19:08:01.703 に答える