html - 淡出、暂停,然后淡入元素 - 仅限 CSS

标签 html css css-animations

我正在尝试淡出一个元素,让该元素淡出,比如说 5 秒,然后再淡入该元素。我正在尝试仅使用 CSS 而不是 jQuery 来实现这一目标。

目前我已经设置了两个元素在 2 秒后开始淡出,淡出持续时间为 2 秒,然后在持续时间结束后立即重新出现。

Here's a fiddle .

还有代码:

CSS:

.hideMe1{
     animation:hideMe 0.5s 1;
    -webkit-animation:hideMe 2s 1; /* Duration of fading and repetitions */
    animation-fill-mode: forwards;

    animation-delay:2s; /* Pause before fade */
    -webkit-animation-delay:2s; /* Safari and Chrome */
    -webkit-animation-fill-mode: backwards;  /* End by showing the content */
} 

.hideMe2{
     animation:hideMe 0.5s 1;
    -webkit-animation:hideMe 2s 1; /* Duration of fading and repetitions */
    animation-fill-mode: forwards;

    animation-delay:2.5s; /* Pause before fade */
    -webkit-animation-delay:3s; /* Safari and Chrome */
    -webkit-animation-fill-mode: backwards;  /* End by showing the content */
} 

@keyframes hideMe{
    from {opacity :1;}
    to {opacity :0;}
}

@-webkit-keyframes hideMe{
    from {opacity :1;}
    to {opacity :0;}
}

HTML:

<div class="hideMe1">
I'll fade first
</div>
<div class="hideMe2">
My turn to fade
</div>

如何让每个元素在重新出现之前保持淡出 5 秒(例如)?

最佳答案

要实现该效果,您必须像下面的代码片段一样修改关键帧。

  • 设置animation-duration,使其成为淡出+暂停+淡入的总时间。这里我将持续时间设置为 10 秒(淡出 2.5 秒 + 暂停 5 秒 + 淡入 2.5 秒)。
  • 设置关键帧百分比以匹配预期的持续时间,如下所示:
    • 25% 标记处(不过是 2.5s10s),将 opacity10
    • 5s 暂停时间不过是 10s50%,因此使元素保持其状态直到 75% 标记。重要的是还添加了 75% 关键帧(即使元素保持在状态中),否则元素将从 25% 标记本身开始淡入.
    • 75% 标记开始,使元素的 opacity0 逐渐变为 1 从而产生淡入效果。

注意:我删除了属性的供应商前缀版本以保持演示简单,我还删除了 animation-fill-mode 的重复声明和 -webkit-animation-fill-mode 因为在任何时候浏览器都只会使用一个。 Webkit 浏览器将使用最后出现的带前缀的浏览器,而其他浏览器将使用不带前缀的浏览器(因此会导致跨浏览器差异)。

.hideMe1 {
  animation: hideMe 10s 1;
  animation-fill-mode: forwards;
  animation-delay: 2s;
}
.hideMe2 {
  animation: hideMe 10s 1;
  animation-fill-mode: forwards;
  animation-delay: 2.5s;
}
@keyframes hideMe {
  0% {
    opacity: 1;
  }
  25% {
    opacity: 0;
  }
  75% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<div class="hideMe1">
  I'll fade first
</div>
<div class="hideMe2">
  My turn to fade
</div>

关于html - 淡出、暂停,然后淡入元素 - 仅限 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35870085/

相关文章:

html - 在 &lt;header&gt; 中 float 元素

javascript - 如何更改 jquery.datatable 创建的表中 "next page"、 "prev page"按钮的样式?

html - 将 "+/-"添加到 Bootstrap Accordion 面板作为切换指示器

javascript - 当向内联 block div 添加内容时,它们表现得很奇怪

html - CSS 动画/变换离开屏幕

html - CSS 动画在一定时间后开始

html - CSS 动画重复

css - 如何将 css 类添加到 Django 管理表单

css - Chrome 中的剪辑路径水平白线

html - 有没有办法用纯CSS让div飞进/飞出