300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 微信小程序开发 | 02 - 轮播图实现(swiper组件)

微信小程序开发 | 02 - 轮播图实现(swiper组件)

时间:2024-01-17 21:17:47

相关推荐

微信小程序开发 | 02 - 轮播图实现(swiper组件)

一、实现思路

轮播图基于微信小程序提供的swiper组件(文档)实现。

swiper组件中使用到下列属性:

display-multiple-items:同时显示的滑块数量current:当前所在滑块的indexindicator-dots:是否显示面板指示点autoplay:是否自动切换interval:自动切换时间间隔circular:是否采用衔接滑动previous-margin:前边距,用于露出前一项的一小部分next-margin:后边距,用于露出后一项的一小部分

使用到的事件为bindchange,当 用户手动滑动导致 current 改变时会触发 change 事件,绑定事件处理函数为 handleSwiperChange,在事件处理函数中,设置当前居中显示项。

在wxml中,使用for循环遍历轮播图片数组,加载所有图片项作为swiper-item。

二、实现代码

wxml代码:

<!--index.wxml--><swiper class="cover_swiper" indicator-dots='true' display-multiple-items='1' current='{{ centerItem }}' bindchange='handleSwiperChange' previous-margin='30' next-margin='30' autoplay='true' circular='true' interval='2000'><block wx:for="{{coverList}}" wx:key="id"><swiper-item><view class='imageBox' style='text-align:center'><view class='mask' wx:if='{{ index != centerItem }}'></view><image src="{{item.url}}" mode='aspectFit' /></view></swiper-item></block></swiper>

wxss代码:

/**index.wxss**/.cover_swiper {height: 180px;}.cover_swiper .mask {width: 100%;height: 100%;background-color: rgba(255, 255, 255, 0.5);position: absolute;left: 0;top: 0;}

js代码:

在data中添加以下数据:

// 居中显示项的位置centerItem: 0, // 首页轮播图数据coverList:[{id: 0,url: "xxx"},{id: 1,url: "xxx"},{id: 2,url: "xxx"},{id: 3,url: "xxx"},{id: 4,url: "xxx"}],

与data同级,添加事件处理函数,当用户滑动轮播图时,改变居中显示项的位置:

//轮播图滑动时改变居中项handleSwiperChange(e) {this.setData({centerItem: e.detail.current,})},

三、实现效果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。