前端工程师实现轮播图有好多种方式,有的喜欢使用自己编写的脚本,有的喜欢使用JQurey,有的喜欢使用swiper插件,不过很少有人会单纯的使用CSS来实现轮播图。
使用CSS实现轮播图操作主要使用了伪类:checked,并将lable指向对应的input的id,来实现这个轮播的功能。
首先我们要有一个容器用来防止轮播图,这里使用的p来代替,HTML页面的代码如下:
轮播图CSS样式,这里用的ul-p,需要的话可以再写代码时用图片表示,这里仅仅是简要的表示一下:
label标签用来放置按钮,通过label来控制轮播图的切换,关于其具体的样式在实际开发中进行调整即可。
最后就是实现css轮播图的核心,主要通过使用控制控制margin值来实现轮播的而效果。
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>css实现轮播图</title>
<style>
body {
margin: 0
background: #dfe
}
ul {
margin: 0
padding: 0
list-style: none
}
.my-swiper {
position: relative
width: 800px
height: 450px
margin: 100px auto
overflow: hidden
}
.swiper-list {
position: absolute
top: 0
left: 0
width: 4000px
height: 100%
overflow: hidden
animation: swiper 10s steps(1, end) infinite
transition: left 1s linear
}
.swiper-slide {
width: 800px
height: 100%
float: left
overflow: hidden
}
.swiper-slide a {
display: block
height: 100%
}
.swiper-slide img {
display: block
width: 100%
height: 100%
object-fit: cover
}
/* 分页 */
.pagination {
position: absolute
bottom: 0
left: 0
right: 0
line-height: 45px
background: rgba(255, 255, 255, 0.3)
text-align: center
}
.dot {
display: inline-block
width: 10px
height: 10px
margin: 0 2px
background: #fff
border-radius: 50%
}
/* 橙色小圆点 */
.dot.active {
position: absolute
left: 356px
top: 18px
width: 11px
height: 11px
margin: 0
background: tomato
animation: swiper-dot 10s steps(1, end) infinite
transition: left 1s linear
}
@keyframes swiper {
0%,
100% {
left: 0
}
20% {
left: -800px
}
40% {
left: -1600px
}
60% {
left: -2400px
}
80% {
left: -3200px
}
/* 100% {
left: -3200px
} */
}
@keyframes swiper-dot {
0%,
100% {
left: 358px
}
20% {
left: 376px
}
40% {
left: 395px
}
60% {
left: 413px
}
80% {
left: 432px
}
}
</style>
</head>
<body>
<div>
<ul>
<li class="swiper-slide swiper-slide1">
<a href="javascript:">
<img src="banner.jpg" alt="">
</a>
</li>
<li class="swiper-slide swiper-slide2">
<a href="javascript:">
<img src="banner1.jpg" alt="">
</a>
</li>
<li class="swiper-slide swiper-slide3">
<a href="javascript:">
<img src="banner2.jpg" alt="">
</a>
</li>
<li class="swiper-slide swiper-slide4">
<a href="javascript:">
<img src="banner.jpg" alt="">
</a>
</li>
<li class="swiper-slide swiper-slide5">
<a href="javascript:">
<img src="banner1.jpg" alt="">
</a>
</li>
</ul>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span class="dot active"></span>
</div>
</div>
</body>
</html>