在CSS3动画结束时保持最终状态

我在CSS中运行一些设置为opacity: 0;的元素的动画。动画类应用于click,并且使用关键帧,它将不透明度从0更改为1(以及其他事情)。

不幸的是,当动画结束时,元素返回opacity: 0(在Firefox和Chrome中)。我的自然想法是动画元素保持最终状态,覆盖它们的原始属性。这不是真的吗?如果不是,我如何让元素这样做?

代码(不包括有前缀的版本):

@keyframes bubble {
0%   { transform:scale(0.5); opacity:0.0; }
50%  { transform:scale(1.2); opacity:0.5; }
100% { transform:scale(1.0); opacity:1.0; }
}
300759 次浏览

尝试添加animation-fill-mode: forwards;。例如,简写可以这样使用:

-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */
animation: bubble 1.0s forwards;

如果你使用更多的动画属性,速记为:

animation: bubble 2s linear 0.5s 1 normal forwards;

这给:

  • bubble动画名
  • 2s持续时间
  • linear定时功能
  • 0.5s延迟
  • 1迭代计数(可以是'infinite')
  • normal方向
  • forwards填充模式(设置'向后'如果你想兼容使用结束位置作为最终状态[这是为了支持已关闭动画的浏览器]{并且只回答标题,而不是你的特定情况})

可用时间函数:

ease | ease-in | ease-out | ease-in-out | linear | step-start | step-end

可用的方向

normal | reverse | alternate | alternate-reverse

如果不使用简写版本:确保animation-fill-mode: forwards是动画声明的,否则它将不起作用…

animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;

vs

animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;
< p >使用 animation-fill-mode:前锋;< / >强

animation-fill-mode: forwards;

元素将保留由最后一个关键帧设置的样式值(取决于animation-direction和animation-iteration-count)。

注意:在ie9和更早的版本中不支持@keyframes规则。

工作示例

div {
width: 100px;
height: 100px;
background: red;
position :relative;
-webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */
animation: bubble 3s forwards;
/* animation-name: bubble;
animation-duration: 3s;
animation-fill-mode: forwards; */
}


/* Safari */
@-webkit-keyframes bubble  {
0%   { transform:scale(0.5); opacity:0.0; left:0}
50%  { transform:scale(1.2); opacity:0.5; left:100px}
100% { transform:scale(1.0); opacity:1.0; left:200px}
}


/* Standard syntax */
@keyframes bubble  {
0%   { transform:scale(0.5); opacity:0.0; left:0}
50%  { transform:scale(1.2); opacity:0.5; left:100px}
100% { transform:scale(1.0); opacity:1.0; left:200px}
}
<h1>The keyframes </h1>
<div></div>

我有一个问题使用forwards:至少在Chrome中,即使在动画结束后,渲染器仍在吸收图形资源,使应用程序响应较差。

一种不会引起这种麻烦的方法是使用EventListener

CSS动画会触发事件,所以你可以在动画结束时使用animationend事件进行干预。

CSS

.fade_in {
animation: fadeIn 2s;
}


@keyframes fadeIn {
from {
opacity: 0;
}


to {
opacity: 1;
}
}

JavaScript

const element = document.getElementById("element-to-be-animated");


element.addEventListener("animationend", () => {
// Set your final state here. For example:
element.style["opacity"] = 1;
}, { once: true });

选项once: true告诉引擎在事件监听器执行后删除它,让你的应用程序保持新鲜和干净。

我已经创建了JSFiddle来展示它是如何工作的。