小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
往常我们实现轮播图,都是要通过大量的JS代码,才能够实现。但在前端越发壮大的今天,CSS已经是非常强的了,已经完全可以通过纯CSS实现轮播图了,接下来就让我通过几行代码来代大家实现纯CSS版的轮播图。
轮播图原理
如上图,右侧黑色方框是一个视口,左侧红色方框是四张图片。
每次滑动的时候,让当前的图片的中线与视口的中线对齐,并停下,就可以实现轮播效果了。当然每张图片的左边线(右边线)和视口的左边线(右边线)对齐也是可以的。
实现
- 我们可以把轮播图设置为一个组件,目录结构如下。
- 首先我们需要现书写一个容器
// swipe.vue
<template>
<div class="swipe">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'Swipe',
props: {
list: {
type: Object,
default: []
}
}
}
</script>
<style lang="scss" scoped>
.swipe {
white-space: nowrap;
overflow: auto;
scroll-snap-type: x mandatory;
}
</style>
- 接着是每个录播图的页面
// swipe-item.vue
<template>
<div class="swipe-item">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'SwipeItem'
}
</script>
<style lang="scss" scoped>
.swipe-item {
display: inline-block;
width: 100%;
height: auto;
scroll-snap-align: center;
}
</style>
- 然后是导出这个两个组件。
// index.js
import Swipe from './swipe.vue';
import SwipeItem from './swipe-item.vue';
export {Swipe, SwipeItem};
注意:scroll-snap-align如果只指定了一个值,则第二个值默认为相同的值。这两个值分别指定父容器和子容器的对齐方式。
好,今天就到这里了,今天努力的你依然是最棒的。Bye Bye!!!