使用不透明动画显示隐藏元素

Showing an hidden element with an opacity-animation

我隐藏了一个 #foo 元素,我需要用 zoomIn css 动画显示它(将元素从 opacity:0 带到 opacity:1.

这是我正在使用的代码:

CSS

#foo {
  opacity: 0;
  ...
}

// Zoom In animation
@keyframes zoomIn {
  0% {
    opacity: 0;
    transform: scale3d(.3, .3, .3);
  }
  50% {
    opacity: 1;
  }
}

.zoomIn {
  animation: zoomIn .2s ease-in-out 0s both;
}

JS

$(document).ready(function() {
    $("#foo").addClass("zoomIn");
});​

通过上面的代码,我看到了动画,然后 #foo 元素又消失了。它不包含 opacity:1。 怎么解决?

你需要定义动画结束时会发生什么,这可以用"forwards" 属性 of animation-fill-mode来完成,这需要动画有一个结束(可以不是以 50% 结束,必须以 100% 或从-到结束)所以更改:

.zoomIn {
    animation: zoomIn .2s ease-in-out 0s both;
}

至:

.zoomIn {
     animation: zoomIn .2s ease-in-out 0s forwards;
}

两者同时使用,就是说元素应该同时使用forwards和backwards,其中forwards是动画的"end",backwards是动画的"beginning"。因此,您将拥有不透明度:0 和不透明度:1,显然向后的值是两者中较强的一个。

关于关键帧

作为对 Slugge post 的补充,我想知道你为什么在 50% 结束动画。我认为您应该在 100% 处结束(特别是如果您希望 opacity 保持在 1 处)。 或者您可以使用 from {} to {}.

而不是 0% {} 100% {}
@keyframes zoomIn {
  0% {
    opacity: 0;
    transform: scale3d(.3, .3, .3);
  }
  100% {
    opacity: 1;
  }
}

关于另一个解决方案

我认为只定义 transition 和 "active" class 而不是使用 Keyframes.[=23 会更容易=]

#foo {
  opacity: 0;
  transition: opacity 0.2s ease-out;
}

#foo.active {
  transform: scale3d(.3, .3, .3);
  opacity: 1;
}

然后

$(document).ready(function() {
    $("#foo").addClass("active");
});​

您可以添加 transition transform 以及 transition: opacity 0.2s ease-out, transform 0.2s ease-out;transition: all 0.2s ease-out;

祝你好运'