我尝试使用css在3张图片之间进行交叉淡入淡出。
我是@keyframes的新手,所以我很难让它发挥作用。
下面是html和css代码片段:
的index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="cf">
<img class="bottom" src="assets/1.png" />
<img class="top" src="assets/2.png" />
<img class="bottom" src="assets/3.png">
</div>
</body>
</html>
的style.css:
#cf {
position: relative;
height: auto;
width: auto;
margin: 0 auto;
}
#cf img {
position: absolute;
left: 0;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
#cf img {
animation-name: cf3FadeInOut;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
animation-duration: 6s;
animation-direction: alternate;
}
#cf img:nth-of-type(1) {
animation-delay: 4s;
}
#cf img:nth-of-type(2) {
animation-delay: 2s;
}
#cf img:nth-of-type(3) {
animation-delay: 0;
}
@keyframes cf3FadeInOut {
0% {
opacity: 1;
}
17% {
opacity: 1;
}
25% {
opacity: 0;
}
92% {
opacity: 0;
}
100% {
opacity: 1;
}
}
现在,动画表现得很奇怪,随机动画时间从一个图像闪烁到另一个图像。
答案 0 :(得分:4)
您接近正确的解决方案。 animation-direction: alternate;
导致动画向后运行&#34;一旦达到100%。在关键帧中定义了奇数时间后,这会导致不均匀的转换:
keyframe 0% 17% 25% 92% 100% 92% 25% 17% 0% 17% ... infinite
state :1 1 0 0 1 0 0 1 1 1
time in state : 17% 62% 0% 62% 34%
transition time: 8% 8% 8% 8%
将关键帧简化为偶数时间,你应该没问题。如果时间分布均匀,您根本不需要animation-direction
。您可以通过更改关键帧的animation-duration
和图片的animation-delay
来轻松调整时间。
#cf img {
animation-name: cf3FadeInOut;
animation-timing-function: ease-in-out;
/* if you only want to cycle a finite amount of times,
simply change 'infinite' with # of iterations you need */
animation-iteration-count: infinite;
animation-duration: 6s;
animation-direction: alternate; /* not strictly necessary */
position:absolute;
}
#cf img:nth-of-type(1) {
animation-delay: 5s;
}
#cf img:nth-of-type(2) {
animation-delay: 3s;
}
#cf img:nth-of-type(3) {
/* add some delay for the first picture as well */
animation-delay: 1s;
}
@keyframes cf3FadeInOut {
/* distributing times evenly */
0% {
opacity: 1;
}
25% {
opacity: 0;
}
75% {
opacity: 0;
}
100% {
opacity: 1;
}
}
&#13;
<div id="cf">
<img class="bottom" src="http://lorempixel.com/200/100/sports/1" />
<img class="top" src="http://lorempixel.com/200/100/sports/2" />
<img class="bottom" src="http://lorempixel.com/200/100/sports/3">
</div>
&#13;
严格来说,前两个转换略有不同,因为它们转换为opacity:1
的图片而不是褪色图片并且时间略有不同,但差异几乎不可见,并且与之相比不值得付出努力由此产生的代码复杂性。