我正在尝试淡出一个元素,让该元素淡出,比如说 5 秒,然后再淡入该元素。我正在尝试仅使用 CSS 而不是 jQuery 来实现这一目标。
目前我已经设置了两个元素在 2 秒后开始淡出,淡出持续时间为 2 秒,然后在持续时间结束后立即重新出现。
还有代码:
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.5s
的10s
),将opacity
从1
到0
。 5s
暂停时间不过是10s
的50%
,因此使元素保持其状态直到75%
标记。重要的是还添加了75%
关键帧(即使元素保持在状态中),否则元素将从25%
标记本身开始淡入.- 从
75%
标记开始,使元素的opacity
从0
逐渐变为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/