JQuery动画回调

时间:2011-06-26 19:07:02

标签: javascript jquery animation

我有一个简单的页面,使用2个函数来回动画一个框:animateLeft和animateRight。当我以这种方式调用动画时,它可以正常工作:

$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft);

然而,当我这样称呼它时:

$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft());

函数animateLeft()不会等到动画完成后再执行。立即调用animateLeft(),导致堆栈溢出。有人可以帮我理解这两行之间的区别以及它们为什么表现不同。

完整的申请如下所示。

<head>
<script src="../JSCommon/jquery-1.5.1.min.js"   type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {

   var stop = false;

   $(document).keydown(function(event) {
      stop = !stop;
      if (!stop)
         animateRight();        
   });

   function animateRight() {
      if(!stop) {
         console.log('animateRight');
         $("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft);
      }
   }

   function animateLeft() {
      if(!stop) {
         console.log('animateLeft');
         $("#divTestBox3").animate({ "left" : "20px" },1000,animateRight);
      }
   }        

});
</script>

</head>

<body>
  <div style="height: 40px;">
          <div id="divTestBox3" style="height: 20px; width: 20px; left: 20px; background-color: #89BC38; position: absolute;"></div>
  </div>
  <p>Press any key to start/stop the animation</p>
</body>

3 个答案:

答案 0 :(得分:1)

animateLeft

引用是函数本身。

animateLeft()

是函数animateLeft调用,没有任何参数。它评估该函数返回的任何内容。

答案 1 :(得分:1)

当你使用...animate(..., animateLeft())时,这是取animateLeft函数的结果并将其作为参数传递(这就是它立即执行的原因)。当您使用...animate(..., animateLeft)时,会将函数本身作为参数传递。在后一种情况下,jQuery使用该函数作为完成处理程序,因此在动画结束时将调用它。

答案 2 :(得分:0)

当你通过animateLeft时,它指的是一个函数。但是当您通过animateLeft()时,它会引用此函数的结果,因此当您调用animate()时,它会立即执行。