当div穿过特定位置时的火焰动画

时间:2013-01-08 19:14:08

标签: html jquery-animate jquery

enter image description here 上图说明了我的情景。当用户点击按钮时,我正在使用Jquery div函数将Animate()从位置'A'[100,100]移动到位置'C'[100,500],在此重定位期间,{{1} }应该跨越位置'B'[100,250]。那时,当它穿过位置B时,我需要发射另一个动画。

与此问题相关我已经浏览了很多并找到this链接。但它没有接受的答案。此外,Jquery有一个名为div的事件,但不幸的是它仅与Change兼容。我的问题是,如果真的不存在,我们可以手动处理jquery中的form elementspostionChanged等事件吗?还是有任何可行的方法可以满足我的需要。

谢谢..!

3 个答案:

答案 0 :(得分:1)

您需要通过每个步骤测试动画并运行一个函数来测试位置。这来自API文档,可以很容易地重新用于动画。

$('li').animate({
  opacity: .5,
  height: '50%'
},
{
  step: function(now, fx) {
    var data = fx.elem.id + ' ' + fx.prop + ': ' + now;
    $('body').append('<div>' + data + '</div>');
  }
});

我为它做了一个小提琴。 http://jsfiddle.net/MatthewDavis/6g8aP/1/

答案 1 :(得分:1)

jQuery.animate采用支持以下方法的选项参数(来源)[http://api.jquery.com/animate/]

  

步骤类型:Function(Number now,PlainObject fx)一个函数   在动画的每一步之后调用。

在您的情况下,代码看起来像:

$('div').animate({
  left: 500
}, {
  step: function(now, fx){
    if (parseInt(now, 10) === 250){
      // call your animation method here.
    }
  }
})

答案 2 :(得分:1)

这是一个有效的解决方案: 我也使用了步骤事件

<强> HTML

<div id="#wrapper">
  <div class="left"></div>
  <div class="right"></div>
  <div class="dot"></div>
</div>
<button class="go">GO!</button>

<强> CSS

#wrapper {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.left, .right {
  position: absolute;
  top: 25px;

  width: 100px;
  height: 100px;
}
.left {
  z-index: 1;
  left: 25px;
  background-color: red;
}
.right {
  right: 25px;
  background-color: green;
}

.dot {
  position: absolute;
  top: 72.5px;

  width: 5px;
  height: 5px;
  left: 50%;
  margin-left: 2.5px;

  background-color: blue;
}

button.go {
  display: block;
  position: absolute;
  top: 150px;
  left: 25px;
}

<强>的jQuery

var $left = jQuery('.left');
var $right = jQuery('.right');
var $button = jQuery('button.go');
var $dot = jQuery('.dot');

var rightPos = $right.offset().left;
var dotPos = $dot.offset().left;
var thread = undefined;
var animationStarted = false;

$button.click(function() {
  $left.animate({
    'left': rightPos
  }, {
    duration: 1000,
    specialEasing: {
      'left': 'easeOutQuad'
    },
    step: function(now, fx) {
      if (!animationStarted && now +$left.width() > dotPos) {
        if (thread) { clearTimeout(thread); }
        thread = setTimeout(function() {
          animation();
          animationStarted = true;
        }, 0);
      }
    },
    complete: function() {
      $(this).after('<div>Animation complete.</div>');
    }
  });
});

function animation() {
  $right.animate({
    'background-color': '#0000ff'
  }, {
    specialEasing: {
      'background-color': 'easeOutQuad'
    }
  });
};

注意,我在step-function中使用了setTimeout来调用其他上下文中的第二个动画。我不确定在一个正在运行的动画中运行 .animate()调用是否合适。为了保持顺畅,我认为最好这样做。有谁知道呢?

另一点是变量 animationStarted 。它只记得我们是否调用了第二个动画。这是确保不在其他动画的步骤事件中调用复杂动画的另一件事。通过这种方式,我们肯定只称它一次。

DEMO