要停止使用$ .animate中没有选择器的所有其他动画,并带有step()?

时间:2018-12-22 12:49:05

标签: javascript jquery animation

我正在使用选择器中的数组对对象进行动画处理,由于特定原因,选择器中的数组被卡在另一个SO post I made中。

如何停止从任意数组值开始的其他动画?例如:$({ x: 0 }).animate({

例如:

$({ x: 0 }).animate({
      x: 500
  }, {
      easing: 'linear',
      duration: 15000,
      step: function(now, fx) {
          // $(this).stop();
          var current_styles = $(selector).attr('style'),
              current_styles = string = current_styles.split(" ");

          var x = parseFloat(current_styles[1].replace('px', '').replace(';', ''));

          if ('x' === fx.prop) {
              x = now;
          }

          $(selector).attr({ style: 'margin-left: ' + x + 'px;' });

      },
      complete: function() {
          //
      }
  });

HTML:

<div class="row row_1"><button data-id="1">GO</button><div class="box" style="margin-left: 0;"></div></div>
<div class="row row_2"><button data-id="2">GO</button><div class="box" style="margin-left: 0;"></div></div>
<div class="row row_3"><button data-id="3">GO</button><div class="box" style="margin-left: 0;"></div></div>
<div class="row row_4"><button data-id="4">GO</button><div class="box" style="margin-left: 0;"></div></div>
<div class="row row_5"><button data-id="5">GO</button><div class="box" style="margin-left: 0;"></div></div>
<div class="row row_6"><button data-id="6">GO</button><div class="box" style="margin-left: 0;"></div></div>

CSS:

.row {
  background-color: green;
  margin-bottom: 1px;
  width: 600px;
}
.box {
  background-color: red;
  height: 20px;
  width: 20px;
  display: inline-block;
}
button {
  float: left;
}

我想在开始播放时停止所有 other 个动画。但是,我无法使用$(selector).stop();,因为它不起作用。

JSFiddle和问题的gif:

https://jsfiddle.net/7vk9d2te/5/ JSFiddle的预期结果(出于我的目的使用错误的格式):

enter image description here

您可以使用step()$(this).stop();内停止动画,但这只会停止您内部的一个动画。

基本上,我需要能够停止所有 other 个动画,然后继续执行刚刚开始的动画。 JS本身的工作原理完全符合预期,我只需要在新动画开始时停止旧动画在轨道中的运行即可。

我不清楚在使用时执行此操作的优雅也不容易的方法

$({ x: 0 }).animate({

谢谢您抽出宝贵的时间来思考我的问题

1 个答案:

答案 0 :(得分:1)

将先前开始的动画存储在变量中,以便您可以访问它(检索当前值并停止它):

var prevAnimation;

function runAnimation(selector) {

  var start = 0;
  if (prevAnimation) {
    start = prevAnimation.get(0).x;
    prevAnimation.stop();
  }

  prevAnimation = $({ x: start }).animate({
      x: 500
  }, {
      easing: 'linear',
      // And so on

更新的小提琴:https://jsfiddle.net/7vk9d2te/9/

-更新-

如果您的动画刚好位于左边缘,则可以通过删除step函数并让jQuery发挥神奇作用来简化代码

function runAnimation(selector) {

  var start = 0;
  if (prevAnimation) {
    start = parseFloat(prevAnimation.css('margin-left'));
    prevAnimation.stop();
  }

  prevAnimation = $(selector)
      .css('margin-left', start + 'px')
      .animate({ 'margin-left': 500 }, {
         easing: 'linear',
         duration: 15000,
      });
}

提琴:https://jsfiddle.net/7vk9d2te/10/