一.原生JS中使用
1.下载swiper : https:
下载下来的是一个压缩包,解压,8+版本的话,打开demo可以查看不同的效果;8-版本直接在根目录下就可以查看。
2.引入swiper
找到:
swiper-bundle.min.js
swiper-bundle.min.css
引入到自己的html文件中
3.使用swiper
在自己的js文件,或者script标签中,总之要保证能获取到swiper,即自己的标签script在swiper-bundle.min.js之后。
创建swiper容器(html元素):
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<div class="swiper-scrollbar"></div>
</div>
导航等组件可以放在Swiper容器之外
可以给.swiper添加宽高/不添加默认就是.swiper父容器的100%
创建swiper实例(需要用到html中设置的类名swiper了):
var mySwiper = new Swiper ('.swiper', {
direction: 'vertical',
loop: true,
pagination: {
el: '.swiper-pagination',
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
scrollbar: {
el: '.swiper-scrollbar',
},
})
二.在React中使用
1.下载安装: yarn add swiper
2.引入基本样式依赖:
import 'swiper/css';
为什么说是基本,因为一些特殊的效果是不包含在默认的swiper中的,需要再次去引入(不需要再安装,yarn add swiper 的时候就安装了)
3.在React组件中引入swiper并使用
import {Swiper,SwiperSlide} from 'swiper/react'
export default function Comp(){
return (
<Swiper
spaceBetween={50} // 每两项之间的间隔
slidesPerView={3} // 每次显示多少项在容器中
// ↓每次切换时的回调,参数就是swiper实例,可以获取到一些有用的属性
onSlideChange={(swiper) => console.log(swiper)}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
</Swiper>
)
}
4.使用拓展功能(autoplay/EffectFade等)
import {Swiper,SwiperSlide} from 'swiper/react'
import {Autoplay,EffectFade} from 'swiper'
export default function Comp(){
return (
<Swiper
modules={[Autoplay,EffectFade]}
autoplay={true} // 开启自动播放
loop={true} // 开启循环播放
effect="fade" // 渐显现切换模式
speed={3000} // 切换过程中的时长,毫秒
delay={5000} // 过多长时间切换到下一项
onSlideChange={(swiper) => console.log(swiper)}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
</Swiper>
)
}