老虎机同时jQuery动画不起作用

时间:2018-07-20 10:12:40

标签: javascript jquery jquery-animate css-animations

我正在尝试为彩票创建老虎机效果。 目标号码已经设置好了,因此一旦按下停止按钮,它便会停止在该号码上。 插槽1一切正常,但是如果我为插槽2和插槽3添加相同的代码,则会造成问题。

下面是代码:

$(document).ready(function() {
  s1 = 1;
  s2 = 1;
  s3 = 1;
  num1 = 6;
  num2 = 5;
  num3 = 7; //Target for 3 slots
  i = 100; //Top margin for animation

  $('#start').click(function() {
    animateslot(50, 0);
  });

  $("#stop").click(function() {
    stopanimationslot1(50, 0);
  });
});


function animateslot(d = 150, i = 0) {
  i = i + 100;
  $('#slot1').animate({
    marginTop: -i
  }, {
    duration: d,
    complete: function() {
      $("#slot1").append("<h3>Column " + s1 + "</h3>");
      s1++;
      if (s1 > 9) {
        s1 = 1;
      }
      console.log(s1);
      animateslot(d, i);
    }
  });

  //If below given code is added it doesn't work**
  /*
  $('#slot2').animate(
  	{
  		marginTop: -i
  	},
  	{
  		duration: d,
  	    complete: function() {
  		  	$("#slot2").append("<h3>Column "+s2+"</h3>");
  		  	s2++;
  		  	if(s2>9){
  		  		s2 = 1;
  		  	}
  		  	console.log("s2="+s2);
  		    animateslot(d, i);
  		}
  	}
  );
  */
}

function stopanimationslot1(d = 150, i = 0, num = 1) {
  $('#slot1').stop();
  i = i + 100;
  $('#slot1').animate({
    marginTop: -i
  }, d, function() {
    if (Math.abs(i / 100) == num1) {
      $('#slot1').clearQueue().stop(false, true);
      console.log("finished");
    } else {
      $("#slot1").append("<h3>Column " + s1 + "</h3>");
      s1++;
      if (s1 > 9) {
        s1 = 1;
      }
      stopanimationslot1(d + 50, i, num);
    }
  });
}
#slot1 h3,
#slot2 h3,
#slot3 h3 {
  width: 100px;
  height: 100px;
  border: 1px solid #999;
  margin: 0;
}

#slotmachine {
  max-height: 100px;
  overflow: hidden;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="javascript:(0);" id="start" class="btn btn-default">Start</a><br><br>
<a href="javascript:(0);" id="stop" class="btn btn-default">Stop</a><br><br>

<div class="container">
  <div class="row" id="slotmachine">
    <div class="col-sm-4" id="slot1">
      <h3>Column 1</h3>
    </div>
    <div class="col-sm-4" id="slot2">
      <h3>Column 1</h3>
    </div>
    <div class="col-sm-4" id="slot3">
      <h3>Column 1</h3>
    </div>
  </div>
</div>

也可以在这里找到:https://jsfiddle.net/sushanttayade123/fqkgvu59/

1 个答案:

答案 0 :(得分:0)

它无法按预期运行的原因在于animateslot(d, i);

按开始后:

  • 插槽1完成并调用animateslot()
  • 插槽2完成,并且呼叫animateslot()

在下一个“动画周期”中,该方法将不会像以前那样运行一次,而是两次,这会导致动作不稳定。每个周期的通话量将以两倍的速度不断增长。

要解决此问题,请在所有动画制作完成后调用animateSlot() 一次,或将每个广告位移入其自身的功能(animateSlot1()animateSlot2(),.. )。

最后的建议:我不建议在每次旋转之后添加新节点,因为这会导致性能下降。