使用纯css实现轮播效果
属性介绍
制作网页尤其是电商类、网站主页等都会遇到轮播图的需求,以往实现轮播图,若不借助第三方插件如swiper等,就需要自行手动实现轮播效果,一大堆的js代码,现在可以使用css实现简单的轮播效果(不包括循环滚动、跳转等)。
scroll-snap-type
scroll-snap-type CSS 属性定义在滚动容器中的一个临时点(snap point)如何被严格的执行。
具体语法,可以参考MDN中的介绍:
scroll-snap-type
scroll-snap-align
scroll-snap-align MDN地址,目前没有中文版本,此属性的作用是在滚动时确定滚动元素与容器元素之间的边界位置,
scroll-snap-align: [ none | start | end | center ]{1,2}
例如,center就代表滚动元素的中心点与容器的中心点药保持位置统一。
效果展示:
代码实现
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css实现轮播效果</title>
<style>
html,
body {
height: 100%;
}
* {
padding: 0;
margin: 0;
}
.swiper {
width: 100%;
height: 100%;
overflow: auto;
white-space: nowrap;
scroll-snap-type: x mandatory;
scroll-snap-stop: always;
}
.swiper__item {
height: 100%;
width: 100%;
scroll-snap-align: center;
display: inline-block;
}
.swiper__item--red {
background-color: red;
}
.swiper__item--green {
background-color: green;
}
.swiper__item--yellow {
background-color: yellow;
}
.swiper__item--pink {
background-color: pink;
}
</style>
</head>
<div class="swiper">
<div class="swiper__item swiper__item--red"></div>
<div class="swiper__item swiper__item--green"></div>
<div class="swiper__item swiper__item--yellow"></div>
<div class="swiper__item swiper__item--pink"></div>
</div>
<body>
</body>
</html>
结尾
借助上述属性,可以实现简单的轮播效果,避免了引入第三方插件或者自行实现效果是的大量代码,但是此效果只能应对简单的轮播需求,涉及循环播放、点击跳转等,还需要自行实现。
tips:
点滴记录,汇聚江河