声明
import 'swiper/components/navigation/navigation.scss';
import 'swiper/swiper.scss';
import SwiperCore, { Autoplay } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
SwiperCore.use([Autoplay]); //需要自动播放要加Autoplay,需要前进后退按钮加Navigation
使用
<Swiper spaceBetween={20} slidesPerView={1} loop={true} autoplay initialSlide={1}>
{list.map((item, index) => (
<SwiperSlide key={index}>
内容{item}
</SwiperSlide>
))}
</Swiper>
参数说明
<Swiper
spaceBetween={20} //间距
slidesPerView={2} //显示的个数
direction={'vertical'} //定义横向还是竖向,默认横向,这里vertival为竖向
autoplay={{ //autoplay即可使用默认数据进行轮播
delay: 3000, //轮播间隔,默认3000
stopOnLastSlide: false, //是否最后一项轮播后停止,默认false,最后一项后会重置到第一个,loop=true时该属性无效
disableOnInteraction: false, //手动触发轮播后,是否停止自动轮播,默认为true,鼠标操作后会停止
}}
speed={800} //滑动速度,800毫秒滑动一项,默认为300
loop={true} //是否循环,循环原理是复制swiperslide,默认false
initialSlide={2} //起始位置,需要手动调至第一项(没懂规律)
breakpoints={{
// 宽高比大于等于1.7时显示3个,大于等于1.9时显示2个;只有部分不需要变换布局方式和逻辑结构的参数支持断点设定,如slidesPerView、slidesPerGroup、 spaceBetween,而像slidesPerColumn、loop、direction、effect等则无效
'@1.7': { slidesPerView: 3 },
'@1.9': { slidesPerView: 2 },
}}
onSwiper={(swiper) => {
//鼠标悬浮暂停效果
swiper.$el[0].addEventListener('mouseover', () => swiper.autoplay.stop());
//鼠标移开后继续自动滚屏效果
swiper.$el[0].addEventListener('mouseleave', () => swiper.autoplay.start());
}}
>
样式调整
根据实际宽高设置swiper最外层宽高
.swiper-container {
width: 100%;
height: 100%;
}
不能手动调整每一项的css大小/定位/边距等样式,否则滚动会出问题,所有调整查看文档对应参数解决。