纯CSS实现图片自动切换,鼠标点击切换相结合
图片自动切换实现原理:使用一个div并设置溢出隐藏来只显示一次一张图片,同时设置另一个div(总图片div),尺寸为所有图片横排的总尺寸宽高,作为动画顺序播放,然后使用css3动画,通过对div(总图片div)进行位移,从而达到显示不同的图片,每次偏移一个图片的宽度,即可显示下一张图片。5张图片,需要切换4次。
鼠标实现图片切换原理:通过设置每个超链接的宽度高度,并使用position定位到指定位置,编写每一个超链接的动画来分别切换相应图片的位置,使用hover,当鼠标放在指定超链接上时,实现指定的动画切换到目标图片上。
代码展示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>图片切换</title>
<style type="text/css">
html,body{height: 100%;background-image: url(img/bac.jpg);background-repeat: no-repeat;background-size: 100% 100%;}
*{margin: 0;padding: 0;}
#main{
width: 800px;height: 460px;
overflow: hidden;position: absolute;left:22.5%;top: 15%;border-radius: 20px;
}
#all-picture{
height:460px;
width: calc(800px * 5);/*如果加图片自行添加数目我这里5张图片所以宽度为5张图片横排的总尺寸,注意添加图片数目之后,动画内的参数也要相应的改变*/
animation: switch ease 15s infinite ;z-index: 9;
}
#all-picture img{
width:800px;height: 440px;float: left;
}
#all-picture:hover{animation-play-state: paused;}
@keyframes switch{/*每个图片切换有两个阶段:位移切换和静置。所以中间的效果可以任意定制,我这里在每个阶段切换时都有一定的时间来静置*/
0%,10%{margin-left: 0;}
20%,30%{margin-left: -800px;}
40%,50%{margin-left: -1600px;}
60%,70%{margin-left: -2400px;}
80%,90%{margin-left: -3200px;}
100%{margin-left: 0px;}
}
@keyframes picture1{
0%{margin-left: -3200px;}
100%{margin-left: 0px;}
}
@keyframes picture2{
0%{margin-left: 0px;}
100%{margin-left: -800px}
}
@keyframes picture3{
0%{margin-left: -800px;}
100%{margin-left:-1600px}
}
@keyframes picture4{
0%{margin-left: -3200px;}
100%{margin-left:-2400px}
}
@keyframes picture5{
0%{margin-left: 0px;}
100%{margin-left:-3200px}
}
#a1:hover ~ #all-picture{animation: picture1 ease 0.5s forwards;}
#a2:hover ~ #all-picture{animation: picture2 ease 0.5s forwards;}
#a3:hover ~ #all-picture{animation: picture3 ease 0.5s forwards;}
#a4:hover ~ #all-picture{animation: picture4 ease 0.5s forwards;}
#a5:hover ~ #all-picture{animation: picture5 ease 0.5s forwards;}
.num1{width: 160px;height: 20px;position: absolute;top:440px;left: 0px;}
.num2{width: 160px;height: 20px;position: absolute;top:440px;left: 160px;}
.num3{width: 160px;height: 20px;position: absolute;top:440px;left: 320px;}
.num4{width: 160px;height: 20px;position: absolute;top:440px;left: 480px;}
.num5{width: 160px;height: 20px;position: absolute;top:440px;left: 640px;}
.num1,.num2,.num3,.num4,.num5{text-align: center;line-height: 20px;}
a:hover{background-color:black;opacity:1;color: yellow;font-size: large;font-weight: bolder;}
a{opacity:0.5;color:white;background-color: #000000;}
a:hover ~ #all-picture:hover{animation-play-state: paused;}
</style>
</head>
<body>
<div id="main">
<a id="a1" class="num1">1</a>
<a id="a2" class="num2">2</a>
<a id="a3" class="num3">3</a>
<a id="a4" class="num4">4</a>
<a id="a5" class="num5">5</a>
<div id="all-picture">
<img src="img/picture1.png" >
<img src="img/picture2.jpg" >
<img src="img/picture3.jpg" >
<img src="img/picture4.jpg" >
<img src="img/picture5.jpg" >
</div>
</div>
</body>
</html>
最终效果如下
css实现图片自动切换,鼠标点击切换相结合