将CSS动画与JQuery相结合,同时保持其平滑度



我正在尝试使用CSS3和jQuery构建传统的老虎机,但我遇到了一些问题。我从CSS3动画开始,它无限运行,直到有人触发事件(按钮或类似事件)。在我们进一步讨论之前,这里是 CSS:

@keyframes animation-one {
  100% {
      margin-top: -960px;
  }
}
.slots-one {
  margin-top: -5px;
  border-left: 7.5px solid #38465a;
  animation: animation-one 2s linear infinite;
}

它意味着无限期地播放,直到触发该事件,然后我想顺利过渡到动态选择数字。我看不出如何在CSS中做到这一点,所以我决定混合一些jQuery,这是我的结果:

.slots-one {
  margin-top: -5px;
  border-left: 7.5px solid #38465a;
}
.anim-one {
  animation: animation-one 2s linear infinite;
}
/*in order for the animation to be smooth, i needed to maintain the same speed.
 i know the height of the div is 1150px with a -5 margin-top so i divided the
 seconds of the current animation (2) by the total height then 
 multiplied it with the new dynamic height i wanted to enforce. */
var seconds = (2 / 1150) * 750; //750 being a random number between 0 and 1150
var margin = -5-750;
$('.board.slots-one').on('animationiteration', function () {
  $(this).removeClass('anim-one')
         .animate({
           "margin-top": margin+"px"
         }, seconds.toString()+"s", "linear") //i figured that an easing wouldn't look too good.
})

正如我所料,动画断断续续,没有按照我想要的方式混合。我在底部留下了一些对动画的引用。

<小时 />参考资料:
CSS3 动画CSS3 动画 + jQuery 动画<小时 />所以我的问题是 1) 如果这甚至可能,如果是这样,我该如何实现这一目标?2)如果不是,我的选择是什么?谢谢。

您可以使用

jquery 来设置margin-top,并使用 CSS transition来控制计时。

喜欢这个:

$('.board.slots-one').on('animationiteration', function () {
    $(this)
    .removeClass('anim-one')
    .css({
        'margin-top': margin,
        'transition': 'all ' + seconds.toString() + 's linear'
    })
}

最新更新