前言
往常我们实现轮播图,都是要通过大量的 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.jsimport Swipe from './swipe.vue';import SwipeItem from './swipe-item.vue';
export {Swipe, SwipeItem};
复制代码
好,今天就到这里了,今天努力的你依然是最棒的。Bye Bye!!!
评论