【问题标题】:css3 animations using "natural" property value使用“自然”属性值的 css3 动画
【发布时间】:2015-06-24 20:53:00
【问题描述】:

我想定义一个 CSS3 动画,在动画过程中的某些时候,它使用属性的自然值,就好像没有应用动画一样。

例如

@keyframes fadeblue
{
  0%
  {
    background-color: natural;
  }
  100% 
  {
    background-color: blue;
  }
}    
.thing1
{
  background-color: red;
  animation: fadeblue 2s;
}
.thing2
{
  background-color: green;
  animation: fadeblue 2s;
}

thing1 将从红色变为蓝色,而 thing2 将从绿色变为蓝色。 在 0% 关键帧中,我应该使用什么值代替 natural

我尝试过继承和透明,但都没有达到预期的效果。

注意我知道这可以通过 JavaScript 解决方案来完成,但如果可能的话,我更喜欢纯 css3 解决方案。

【问题讨论】:

    标签: css animation


    【解决方案1】:

    因此,您似乎无法在关键帧中引用原始颜色。但是,您可以在 keyframes 声明中指定 one keyframe 并让浏览器为您插入颜色。使用仅50% 的关键帧将使用0%(又名from)和100%(又名to)的原始属性。

    有了这些知识,我们还可以使用animation-delay 有效地对动画进行排队,以创建看起来像单个动画但实际上并非如此的动画。

    例如:

    @keyframes fadeblue {
      50% {
        background-color: blue;
      }
    }
    @keyframes fadewhite {
      50% {
        background-color: white;
      }
    }   
    .thing1 {
      background-color: red;
      animation: fadeblue 2s,
                 fadewhite 2s 2s; 
                 /* shorthand here is: animation-name animation-duration animation-delay */
    }
    .thing2 {
      background-color: green;
      animation: fadeblue 2s,
                 fadewhite 2s 2s;
    }
    .thing3 {
      background-color: yellow;
      animation: fadeblue 2s,
                 fadewhite 2s 2s;
    }
    .thing4 {
      background-color: purple;
      animation: fadeblue 2s,
                 fadewhite 2s 2s;
    }
    <div class="thing1">Thing 1</div>
    <div class="thing2">Thing 2</div>
    <div class="thing3">Thing 2</div>
    <div class="thing4">Thing 2</div>

    您会看到元素淡化为蓝色并恢复为原始颜色,然后淡化为白色,然后变为原始颜色。

    jsfiddle 很好。

    【讨论】:

    • 啊哈。好的,这解决了问题中的特定场景,但没有解决其他情况(例如,在动画的一部分应该使用自然色,而不仅仅是在开始时)
    • @DJL 考虑使用我在其他答案中提出的伪元素的解决方案。那里的关键帧确实有更大的灵活性。
    • 公平评论@DJL。我已经调整了答案,希望能提供完整的解决方案
    • 一个有趣的想法。感觉有点hacky,但确实完成了工作。谢谢
    【解决方案2】:

    如果您对.thing1. thing2 使用伪元素(例如:before),将其颜色设置为蓝色,并为opacity 设置动画,则可以实现此目的。这有点工作,但我相信它会是更灵活的解决方案:

    (参见下面的工作演示)

    @keyframes fadeblue {
      0% {
        opacity: 0;
      }
      100% {
        opacity: 1;
      }
    }
    .thing1,
    .thing2 {
      width: 100px;
      height: 100px;
      display: inline-block;
      position: relative;
    }
    .thing1:before,
    .thing2:before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: blue;
      animation: fadeblue 2s infinite;
    }
    .thing1 {
      background-color: red;
    }
    .thing2 {
      background-color: green;
    }
    <div class="thing1"></div>
    <div class="thing2"></div>

    【讨论】:

    • 如果之前和之后的伪元素还没有用于某些东西,这可能是一种方便的方法
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    相关资源
    最近更新 更多