jQuery Transit动画未在for循环中正确执行

jQuery Transit animation not executing within for loop properly

本文关键字:执行 循环 for Transit 动画 jQuery      更新时间:2024-05-03

我正在使用jQuery Transit来为一个不断变化的元素设置动画。

我正在使用for循环为多个长方体设置动画。

javaScript:

<script>
window.onload = function(){
  $('div.test').mouseover(function(){
    for (var i = 0; i < 2; i++){
      console.log(i+' Starting Loop');
      //Rotate box animation
      $('div.test' && '.'+i).transition({
        perspective: '100px',
        rotateY: '-180deg',
        x: '-90px'
      }, 'slow',function(){
        //On completion code.
        $('div.test' && '.'+i).append(' With Changed Text');
        console.log(i + 'Text has been changed');
        //Rotate back
        $('div.test' && '.'+i).transition({
          perspective: '100px',
          rotateY: '0deg',
          x: '0px'
        }, 'slow');
      });
      console.log(i + 'finished the loop');
      alert(i + ' finished loop');
    }
  });
}
</script>

以及HTML:

<body>
<div class='test 0'>
  Box1
</div>
<div class='test 1'>
  Box2
</div>
</body>

它的工作原理是使长方体移动,进行适当的更改,然后移回其原始位置。

然而,与其等待第一个动画完成后再进行for循环的下一次迭代,不如等待for循环完成后再执行$.transition()函数。

因此,当调用$.transition()函数时,i = 2。因此,$.append()函数正在附加到一个不存在的类为".2"的元素。

有什么方法可以确保动画在循环中正确执行吗?

注意这是我真实代码的简化版本。我通常会为每个框添加不同的值。我还在迭代一个列表,这个列表可能比2长。

EDIT我通过递归迭代数组找到了一个解决方案。在这里。

我认为您已经有了来回动画框所需的代码,但是,您的for循环正在立即执行(从而几乎同时启动转换)。

看看这个例子。您应该能够根据需要多次修改它以循环。http://jsfiddle.net/zca33/

此外,我不确定是否可以将jQuery选择器与&amp;,至少,这不是首选的方法。请参阅:http://api.jquery.com/multiple-selector/

EDIT:由于您试图在ajax调用成功时执行动画,因此可以通过CSS类针对特定框。请参阅:http://jsfiddle.net/zca33/2/

这是一个官方答案,下面是我的新javaScript代码。

<script>   
function rotateBox(list){
  if (list.length <= 0){
    return;
  }
  var i = list.pop();
  console.log("i: "+i);
  $('div.test' && '.'+i).transition({
    perspective: '100px',
    rotateY: '-180deg',
    x: '-90px'
  }, 'slow',function(){
    //On completion code.
    $('div.test' && '.'+i).append(' With Changed Text');
    console.log(i + 'Text has been changed');
    //Rotate back
    $('div.test' && '.'+i).transition({
      perspective: '100px',
      rotateY: '0deg',
      x: '0px'
    }, 'slow', function(){
      //Recursion!
      rotateBox(list);
    });
  });
}
window.onload = function(){
  //a list of arbitrary values that match with a <div> class
  list = [0, 1];
  $('div.test').mouseover(function(){
    rotateBox(list);
    //Just in case you feel like running through it again
    list = [0, 1];
  });
};
</script>

还有一个演示:http://jsfiddle.net/bHsL3/6/.