React项目使用Swiper实现多滑块居中凸起轮播的配置咨询
React Swiper 实现居中滑块高度高于两侧的配置方案
依赖安装
首先安装Swiper对应React版本的依赖:
npm install swiper # 或 yarn add swiper
核心配置项
你需要在Swiper组件上配置以下必填参数:
centeredSlides: true:开启滑块居中对齐,保证当前激活的滑块始终在视口中间位置slidesPerView: 'auto':允许自定义单个滑块宽度,灵活控制同屏展示的滑块数量,也可根据需求固定为数值(比如3代表同屏展示3个滑块)spaceBetween:配置滑块之间的间距,按需调整即可- 可选配置
loop: true:开启无限滚动效果
完整代码示例
组件代码
import { Swiper, SwiperSlide } from 'swiper/react'; import { Navigation, Pagination } from 'swiper/modules'; // 导入Swiper基础样式 import 'swiper/css'; import 'swiper/css/navigation'; import 'swiper/css/pagination'; const CarouselDemo = () => { return ( <Swiper modules={[Navigation, Pagination]} centeredSlides={true} slidesPerView={'auto'} spaceBetween={20} loop={true} navigation pagination={{ clickable: true }} className="custom-swiper" > <SwiperSlide className="custom-slide">滑块1内容</SwiperSlide> <SwiperSlide className="custom-slide">滑块2内容</SwiperSlide> <SwiperSlide className="custom-slide">滑块3内容</SwiperSlide> <SwiperSlide className="custom-slide">滑块4内容</SwiperSlide> <SwiperSlide className="custom-slide">滑块5内容</SwiperSlide> </Swiper> ) } export default CarouselDemo;
样式代码(核心实现高度差)
Swiper默认给居中激活的滑块添加了swiper-slide-active类名,通过该类名区分样式即可:
/* 滑块默认样式(两侧滑块的样式) */ .custom-swiper .custom-slide { width: 300px; height: 400px; transition: all 0.3s ease; opacity: 0.7; border-radius: 12px; overflow: hidden; } /* 居中激活滑块的样式 */ .custom-swiper .swiper-slide-active { height: 500px; opacity: 1; }
补充说明
- 如果滑块内容为动态高度,可删除固定高度配置,给激活态滑块添加
align-self: flex-start等flex属性适配内容高度即可 - 若要让切换动画更统一,可将Swiper的
speed参数和CSS过渡时间设置为相同数值 - 可根据需求自定义滑块的圆角、阴影、缩放等其他样式,突出居中滑块的视觉效果
内容的提问来源于stack exchange,提问作者Nasrin Mazaheri
相关产品推荐
相关产品推荐

