大家好,我是燐子,今天给大家带来swiper实例
微信小程序中的 swiper
组件是一种用于创建滑动视图的容器组件,常用于实现图片轮播、广告展示等效果。它通过一系列的子组件 swiper-item
来定义滑动视图的每一个页面。
基本用法
以下是一个简单的 swiper
示例代码:
WXML(页面结构)
<swiper
autoplay="true"
interval="3000"
duration="500"
indicator-dots="true"
indicator-active-color="#ff0000"
>
<swiper-item>
<image src="https://example.com/image1.jpg" mode="aspectFill"></image>
</swiper-item>
<swiper-item>
<image src="https://example.com/image2.jpg" mode="aspectFill"></image>
</swiper-item>
<swiper-item>
<image src="https://example.com/image3.jpg" mode="aspectFill"></image>
</swiper-item>
</swiper>
WXSS(样式)
swiper {
width: 100%;
height: 200px;
}
image {
width: 100%;
height: 100%;
}
主要属性
autoplay
:是否自动切换,默认值为 false
。
interval
:自动切换的时间间隔(单位 ms),默认值为 5000
。
duration
:滑动动画时长(单位 ms),默认值为 500
。
indicator-dots
:是否显示面板指示点,默认值为 false
。
indicator-color
:指示点颜色,默认值为 rgba(0, 0, 0, .3)
。
indicator-active-color
:当前选中的指示点颜色,默认值为 #000000
。
circular
:是否采用衔接滑动,默认值为 false
。
vertical
:滑动方向是否为纵向,默认值为 false
。
current
:当前所在滑块的索引,默认值为 0
。
onChange
:切换时触发的事件。
事件
change
:swiper 切换时触发,返回 event.detail
对象,其中包括 current
(当前所在滑块的索引) 和 source
(触发切换的原因)。
示例
以下是一个包含事件处理的示例:
WXML
<swiper
autoplay="true"
interval="3000"
duration="500"
indicator-dots="true"
indicator-active-color="#ff0000"
bindchange="swiperChange"
>
<swiper-item>
<image src="https://example.com/image1.jpg" mode="aspectFill"></image>
</swiper-item>
<swiper-item>
<image src="https://example.com/image2.jpg" mode="aspectFill"></image>
</swiper-item>
<swiper-item>
<image src="https://example.com/image3.jpg" mode="aspectFill"></image>
</swiper-item>
</swiper>
JS
Page({
data: {
current: 0
},
swiperChange(e) {
this.setData({
current: e.detail.current
});
console.log('Current index has changed to:', e.detail.current);
}
});
通过这些属性和事件,可以灵活地控制 swiper
组件,实现各种滑动视图效果。