我是CSS的新手,我一直在使用这段代码。它显示了第一个图像,当我把鼠标放在上面时,它变成了second.jpg,但第三个不起作用。我想把鼠标移到second.jpg,几秒钟后换成third.jpg,几秒后再换成first.jpg,并在鼠标悬停时不断重复。有人能帮我吗?
#cf {
position:relative;
height:400px;
width:273px;
margin:0 auto;
}
#cf img {
position:absolute;
left:0;
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
-o-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
#cf img.top:hover {
opacity:0;
}
<div id="cf">
<img class="top" src="first.jpg" />
<img class="bottom" src="second.jpg" />
<img class="third" src="third.jpg" />
</div>
使用transition
无法连续旋转多个图像,因为转换只指定一次状态更改。因此,使用过渡最多只能在图像中旋转一次。
这个用例的最佳选择是使用CSS3动画,它确实允许循环。假设您有3个图像,并且每个图像在显示下面的图像之前必须可见1s,则总animation-duration
应为3s
。每个图像必须在1s的持续时间内从opacity: 1
变为opacity: 0
,因此动画的关键帧应该以这样的方式指定,即直到33%
(因为33%的3s=1s),图像不透明度为1,而在33.1%
时,它会迅速变为0,并一直保持到结束。
最上面的图像上的动画可以立即开始,但中间和底部的动画应该只有在它们上面的图像完成动画后才开始。所以,中间的图像应该有1s的延迟,底部的图像应该是2s的延迟。
#cf {
position: relative;
height: 200px;
width: 200px;
margin: 0 auto;
}
#cf img {
position: absolute;
left: 0;
}
#cf:hover img {
animation: rotate-in-out 3s linear infinite;
}
#cf:hover img:nth-of-type(1) {
animation-delay: 0s;
}
#cf:hover img:nth-of-type(2) {
animation-delay: 1s;
}
#cf:hover img:nth-of-type(3) {
animation-delay: 2s;
}
#cf img:nth-of-type(2), #cf img:nth-of-type(3) {
opacity: 0; /* make them invisible initially */
}
@keyframes rotate-in-out {
0.1%, 33% {
opacity: 1;
}
33.1%, 100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div id="cf">
<img class="top" src="http://lorempixel.com/200/200/nature/1" />
<img class="bottom" src="http://lorempixel.com/200/200/nature/2" />
<img class="third" src="http://lorempixel.com/200/200/nature/3" />
</div>
在上面的示例中,旋转有点突然(也就是说,它突然从一个图像变到下一个图像)。如果你需要它优雅,那么关键帧应该像下面的片段一样修改:
#cf {
position: relative;
height: 200px;
width: 200px;
margin: 0 auto;
}
#cf img {
position: absolute;
left: 0;
}
#cf:hover img {
animation: rotate-in-out 3s linear infinite;
}
#cf:hover img:nth-of-type(1) {
animation-delay: 0s;
}
#cf:hover img:nth-of-type(2) {
animation-delay: 1s;
}
#cf:hover img:nth-of-type(3) {
animation-delay: 2s;
}
#cf img:nth-of-type(2), #cf img:nth-of-type(3) {
opacity: 0;
}
@keyframes rotate-in-out {
16.5%, 33% {
opacity: 1;
}
49.5% {
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div id="cf">
<img class="top" src="http://lorempixel.com/200/200/nature/1" />
<img class="bottom" src="http://lorempixel.com/200/200/nature/2" />
<img class="third" src="http://lorempixel.com/200/200/nature/3" />
</div>