使用jquery动画 - offset.left不更新

时间:2011-05-31 16:51:04

标签: jquery jquery-animate offset

我试图在屏幕上的几个步骤中为对象设置动画,直到它到达目标为止。但是,offset.left值不会动态变化(或者我做错了,更有可能)。

这就是我所拥有的

var initialOffset = $('#puzzle-transition-object').offset(); //thing to move
var terminalOffset = $('#puzzle-container').offset(); //thing to touch
var dtt = terminalOffset.left - initialOffset.left; //distance to travel
var stepSegment = "+=" + Math.ceil(dtt/8) + "px"; //in left: css format

function bringOutTheDiv(){
  var currentDivPosition = $('#puzzle-transition-object').offset();
  if(currentDivPosition.left < terminalOffset.left){
     console.log("current position"+currentDivPosition.left+": "+terminalOffset.left);
     takeAStep(); 
  }
}

function takeAStep(){
    $('#puzzle-transition-object').animate({
      left: stepSegment,
    }, {
      duration: 50,
      complete: function() {
      //console.log("completed a step");
      }
    });
    bringOutTheDiv();
}

我确实在while循环中使用了它,但是将其分解为另一个函数。基本上,currentDivPosition.left没有更新,我得到一个堆栈溢出错误,虽然div确实一直在屏幕上移动......

谢谢!

1 个答案:

答案 0 :(得分:1)

看起来你应该这样做:

var initialOffset = $('#puzzle-transition-object').offset(); //thing to move
var terminalOffset = $('#puzzle-container').offset(); //thing to touch
var dtt = terminalOffset.left - initialOffset.left; //distance to travel
var stepSegment = "+=" + Math.ceil(dtt/8) + "px"; //in left: css format

function bringOutTheDiv(){
  var currentDivPosition = $('#puzzle-transition-object').offset();
  if(currentDivPosition.left < terminalOffset.left){
     console.log("current position"+currentDivPosition.left+": "+terminalOffset.left);
     takeAStep(); 
  }
}

function takeAStep(){
    $('#puzzle-transition-object').animate({
      left: stepSegment,
    }, {
      duration: 50,
      complete: function() {
      //console.log("completed a step");
      bringOutTheDiv();
      }
    });
}

在回调中给你循环调用 - 应该有帮助:)