代码实现
相比于网上使用较为复杂的方案实现轮播图,本文使用css的Scroll Snap
可以用更少的代码来实现轮播图效果。
具体而言,主要使用两个css代码,分别是scroll-snap-type
和scroll-snap-align
。前者用于确定轮播图吸附轴向,后者用于确定轮播图是初始吸附还是中间吸附还是后面吸附。
下面是HTML代码:
<div class="box">
<div class="box_item box_item--bg1"></div>
<div class="box_item box_item--bg2"></div>
<div class="box_item box_item--bg3"></div>
<div class="box_item box_item--bg4"></div>
</div>
下面是css代码:
.box {
overflow: auto;
/* 如果块宽度为100%,那么它占满一行之后就会换行 */
white-space: nowrap;
scroll-snap-type: x mandatory;
}
.box_item {
display: inline-block;
height: 100px;
width: 100%;
background: pink;
scroll-snap-align: center;
/* 用于实现即使用力拖也要一个接一个展示 */
scroll-snap-stop: always;
}
.box_item--bg1 {
background-color: pink;
}
.box_item--bg2 {
background-color: blue;
}
.box_item--bg3 {
background-color: red;
}
.box_item--bg4 {
background-color: green;
}
效果样式如下: