javascript - 使用jQuery setInterval同步css关键帧动画

标签 javascript jquery css

我遇到了一个问题。我有一个 7000 毫秒的 setInterval 函数,它做了一件小事,还有一个 css3 关键帧动画设置为 7s。最初它完美地同步运行,但经过几次循环/动画时间后,它们开始越来越不同步。所以我想知道在 setInterval 函数中设置的 7000 是否与在 css3 关键帧动画中设置的 7s 相同,或者它们是不同的,因此会随着时间的推移导致这种异常化?

这是一个例子 jsFidle (出于某种原因,它有时表现不同)

带有 setInterval 的 jQuery 动画:

function opacity() {
        $('#jQuery').animate({opacity: 0}, 100);
        $('#jQuery').animate({opacity: 1}, 100);
    }
    setInterval(opacity, 1000);

css 关键帧动画:

@-webkit-keyframes test {
  0%, 100%  {  opacity: 0; }
  10%, 90%  {  opacity: 1; }
}
@-moz-keyframes test {
  0%, 100%   {  opacity: 0; }
  10%, 90%    {  opacity: 1; }
}
@-o-keyframes test {
  0%, 100%   { opacity: 0; }
  10%, 90%   {  opacity: 1; }
}
@keyframes test {
  0%, 100%   { opacity: 0; }
  10%, 90%  { opacity: 1; }
}

最佳答案

JavaScript 可以监听 CSS 动画并有不同的事件:

  • 动画迭代
  • 动画开始
  • 动画结束

在你的例子中,因为你有一个无限迭代,你正在寻找 animationiteration :

animationiteration

The animationend event is fired when an iteration of an animation ends. This event does not occur for animations with an animation-iteration-count of one.

MDN Documentation

请注意,这些事件有其在浏览器上的前缀:

W3C standard         |   Firefox              |   webkit                     |   Opera                 |   IE10
animationstart       |   animationstart       |   webkitAnimationStart       |   oanimationstart       |   MSAnimationStart
animationiteration   |   animationiteration   |   webkitAnimationIteration   |   oanimationiteration   |   MSAnimationIteration
animationend         |   animationend         |   webkitAnimationEnd         |   oanimationend         |   MSAnimationEnd

You can also add a jQuery delay if you want to wait a X number if MS before doing something.

The final code look like this :

$('#css').on('animationiteration webkitAnimationIteration oanimationiteration   MSAnimationIteration', function(){
        $('#jQuery').delay(250)//If you need any kind of delay
        .animate({opacity: 0}, 100)
        .animate({opacity: 1}, 100);
})

Fiddle

关于javascript - 使用jQuery setInterval同步css关键帧动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24411251/

相关文章:

javascript - 如何在 CasperJS 中使用 jQuery?

javascript - jQuery动态输入另一个Input的值

javascript - 我如何使用纯 Javascript "mouse swipe"?

javascript - 使用 React 开发时深度复制对象

jquery - 垂直 CSS Tab,同时保持 div 在部分中的组织

javascript - 如何使日期选择器无法选择某些月份?

javascript - 单击选择选项时如何隐藏选项卡

html - 尝试将我的 <h1> 和 <p> 元素对齐在我的图像左侧

javascript - 创建 jquery 菜单 - json 响应

javascript - React.js - 如何使用来自子项的参数在父项中执行函数