animation: shorthand property vs animation-name:

时间:2017-04-13 14:52:31

标签: css animation chaining

I've searched everywhere to find an answer to this question but I couldn't.

My question is about the shorthand animation property vs the long way around.

When you want to chain two animations together you cannot do the following

animation-name: keyframename1 1s, keyframename2 3s;

that will not work, but if you do the following by dropping the -name it works.

animation: keyframename1 1s, keyframename2 3s;

I cannot find any information online anywhere why you need to drop the name part from the selector for it to work. I understand it's a shorthand property, but doesn't seem to be a long winded way of including 2 keyframes to work one after the other.

Because soon as you declare animation-name: it will only take the first keyframe name and ignore the second one. But animation: is supposed to be for combining various selectors for one keyframe. Not for combining multiple keyframe names.

How would you include two keyframe names to work one after the other without doing it the shorthand way? Is it possible to use the selector of animation-name:? And why doesn't the W3C website explain you can actually chain keyframe name(s) in the shorthand property and not just transition selectors etc.

1 个答案:

答案 0 :(得分:2)

MDN article在我看来非常有见地。

问题是,当您仅指定animation-name时,您也无法指定持续时间。因此,您建议的规则

animation-name: keyframename1 1s, keyframename2 3s; /* this won't work! */

语法无效。您的浏览器可能会将其解释为"我们只应用动画keyframename1",但至少在Firefox中,规则会被完全忽略。实际上我会期待这种行为。

您的第二条规则 有效,并且确实会应用这两种动画。这是因为animation指令将采用动画列表,每个动画都包含名称和持续时间。您可以指定更多内容,例如animation-timing-functionanimation-iteration-countanimation-fill-mode。您未指定的值将设置为默认值。

这最后一句话很重要!当你写下面的

animation-duration: 10s; /* this will be overwritten by the next line */
animation: keyframename1;

持续时间为0s,因为这是animation的默认值,您可以在链接文章中看到。

上述特定指令也各有一个列表。因此,如果要应用多个动画,可以在单个animation规则中完全指定它们,也可以使用其他指令分别设置所有属性。

以下代码段说明了这两种方法。您可以看到结果完全相同。



@keyframes fly-down {
  from { top: 0; }
  to { top: 100px; }
}

@keyframes fly-right {
  from { left: 0; }
  to { left: 100px; }
}

div {
  display: inline-block;
  position: relative;
  padding: 20px;
  border: 1px solid #000;
}

div.method1 {
  animation-duration: 1s, 3s;
  animation-fill-mode: both;
  animation-name: fly-right, fly-down;
}

div.method2 {
  animation: fly-right 1s both,
             fly-down 3s both;
}

<div class="method1">Hi!</div>
<div class="method2">Hi!</div>
&#13;
&#13;
&#13;