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

一、实现思路

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

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

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

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

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

二、实现代码

wxml代码:

<!--index.wxml-->
<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="http://www.bubuko.com/{{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,
})
},
三、实现效果

技术分享图片

?

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

原文:https://blog.51cto.com/u_13640625/3018800

以上是微信小程序开发 | 02 – 轮播图实现(swiper组件)的全部内容。
THE END
分享
二维码
< <上一篇
)">
下一篇>>