【问题标题】:Is it Possible to Randomize an Animation in CSS?是否可以在 CSS 中随机化动画?
【发布时间】:2016-12-21 12:58:32
【问题描述】:

以下动画在三个不同的元素上运行。

我怎样才能使动画随机化,使它们在不同的时间出现?

@keyframes shine{
  10% {
    opacity: 1;
    top: -30%;
    left: -30%;
    transition-property: left, top, opacity;
    transition-duration: 0.7s, 0.7s, 0.15s;
    transition-timing-function: ease;
  }
  100% {
    opacity: 0;
    top: -30%;
    left: -30%;
    transition-property: left, top, opacity;
  }
}

http://jsfiddle.net/nqQc7/1186/

此外,动画之间似乎存在延迟。如何在不增加过渡本身速度的情况下加快动画之间的持续时间?

我尝试添加更多关键帧,但似乎并没有增加动画之间的时间。

【问题讨论】:

  • 您可以使用 javascript 生成一个随机数,然后将其应用为样式,也有 CSS 替代品,例如 SASS 带有允许您执行此操作的模块。

标签: css css-animations


【解决方案1】:

您可以为每个按钮使用不同的动画延迟和动画持续时间值,如下所示:

/**
 * Icon
 */

.icon {
  position: relative;
  overflow: hidden;
  width: 50px;
  height: 50px;
  display: inline-block;
  
  margin: 25px 0 25px 25px;
  border-radius: 5px;
  color: #fff;
  text-decoration: none;
  text-align: center;
  line-height: 50px;
  font-size: 12px;
  font-family: sans-serif;
}

.icon:nth-child(1) { background: cornflowerblue; }
.icon:nth-child(2) { background: salmon; }
.icon:nth-child(3) { background: gray; }

/**
 * The "shine" element
 */

.icon:after {
  
  animation: shine 1s ease-in-out alternate infinite;
  animation-fill-mode: forwards;  
  content: "";
  position: absolute;
  top: -110%;
  left: -210%;
  width: 200%;
  height: 200%;
  transform: rotate(30deg);
  
  background: rgba(255, 255, 255, 0.13);
  background: linear-gradient(
    to right, 
    rgba(255, 255, 255, 0.13) 0%,
    rgba(255, 255, 255, 0.13) 77%,
    rgba(255, 255, 255, 0.5) 92%,
    rgba(255, 255, 255, 0.0) 100%
  );
}

.icon:nth-child(1):after { animation-delay: .1s; }
.icon:nth-child(2):after { animation-delay: .3s; }
.icon:nth-child(3):after { animation-delay: .5s; }

/* Hover state - trigger effect */


/* Active state */



@keyframes shine{
  60% {
    top: -30%;
    left: -30%;
  }
  100% {
    opacity: 0;
    top: -30%;
    left: -30%;
  }
}
<a href="#" class="icon">let</a>
<a href="#" class="icon">it</a>
<a href="#" class="icon">shine</a>

<!--
Forked by:
Nicolas Gallagher - http://jsfiddle.net/KbNq7/
Chris Coyier - http://jsfiddle.net/chriscoyier/hk6z9/1/
-->

【讨论】:

  • 这正是我想要的! :) 但是,动画之间似乎仍然存在延迟;你知道有什么方法可以通过使闪耀动画更频繁地出现(不要与更快混淆)来使效果更加戏剧化。
  • 立即查看片段集。您在动画的前 10% 中设置了闪耀移动,在最后 90% 中设置了不透明度变化,这就是为什么在接下来的移动之间会有很大的延迟,只需更改 @keyframes 范围中的动画步骤百分比和动画持续时间即可设置预期的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 2018-06-16
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
相关资源
最近更新 更多