使用CSS在循环上运行两个不同的同步动画?

时间:2017-06-06 02:29:26

标签: css animation

我正在使用浮动的图像,然后淡出。 (有些则相反,淡入。)它第一次通过循环,但是当它第二次出现时,衰落就会消失。

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
  animation: drift 15s linear infinite, 3s fadeOut 12s ease-in;
}

@keyframes drift {
  from {
    transform: translateX(-175px);
  }
  to {
    transform: translateX(400px);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
<div class="candycane candycane_drift"></div>

2 个答案:

答案 0 :(得分:3)

您可以考虑组合动画并设置关键帧百分比,如下所示:

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
  animation: drift 15s linear infinite;
}

@keyframes drift {
  0% {
    transform: translateX(-128px);
    opacity: 1;
  }
  66% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translateX(400px);
  }
}

   
<div class="candycane candycane_drift"></div>

这样做的缺点是将两个动画绑定到一个缓动设置,但在某些情况下它可能更容易理解并且是一个很好的解决方案。

答案 1 :(得分:0)

我会研究你正在使用的动画速记属性。基本值如下:/ * @keyframes duration |定时功能|延迟| 迭代计数|方向|填充模式|游戏状态名称* /

延迟开始适用于所有动画的第一次迭代,因此我使用了cubic-bezier来应用您正在寻找的后期淡出效果。但是还有其他方法来构建动画,例如,您可以使用多步关键帧来开始动画,以便在80%关键帧进度点淡出。多步动画具有以下格式:

@keyframes late-fade {
  0% {
    opacity: 1;
  }
  /* Adding a step in the middle */
  80% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

这只是获得此效果的一种解决方案,下面的解决方案是使用立方贝塞尔而不是轻松定时功能。

&#13;
&#13;
.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
/* @keyframes duration | timing-function | delay | 
iteration-count | direction | fill-mode | play-state | name */
  animation: drift 15s linear infinite, fadeOut 15s cubic-bezier(.75,0,1,0) infinite;
}

@keyframes drift {
  from {
    transform: translateX(-175px);
  }
  to {
    transform: translateX(400px);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
&#13;
<div class="candycane candycane_drift"></div>
&#13;
&#13;
&#13;

相关问题