css - 在 1 之前停止 CSS3 不透明度动画

标签 css css-animations

我正在尝试为某个 div 不透明度设置动画 from 0 to 0.6,但似乎在动画结束时它跳转到 1

我错过了什么?

#test {
  width: 200px;
  height: 200px;
  background-color: #900;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  -webkit-animation: fadein 2s;
  -o-animation: fadein 2s;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-moz-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-webkit-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-o-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}
<div id="test"></div>

最佳答案

如果您希望元素的 CSS 保留在动画的最后一步,则需要指定 animation-fill-mode: forwards

https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode

Forwards: The target will retain the computed values set by the last keyframe encountered during execution.

#test {
  width: 200px;
  height: 200px;
  background-color: #900;
  animation: fadein 2s forwards;
  -moz-animation: fadein 2s forwards;
  -webkit-animation: fadein 2s forwards;
  -o-animation: fadein 2s forwards;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-moz-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-webkit-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-o-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}
<div id="test"></div>

关于css - 在 1 之前停止 CSS3 不透明度动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44418363/

相关文章:

javascript - 如何从此函数调用返回值?

html - 根据内容大小将 HTML 分成页面

javascript - 在 Javascript 中,如何避免 createTextElement 方法中的 "escaping"?

css - 当笔画有一个 dasharray 时,我怎样才能做一个 SVG 路径绘图动画?

html - float 和 IE6 的问题

html - 粘性页脚 + 固定宽度 + 背景色

css - 悬停时更改大小 : ugly flicker/"shaking" effect

javascript - Safari 12 css 动画效果不佳

javascript - JS操作CSS 3D旋转动画

css - 背面可见性选择器对我不起作用