在很多App的首页顶端都会有一个广告轮询视图(大多数App都在这个位置),轮询广告至少是3页。通常轮询广告下方中心的位置是若干个小点(有的可能是其他效果,如横杠),小点数目和广告页面数目相同,当显示某个广告页面时,表示该广告页面的小点就会处于选中状态(一般是变颜色)。通过点击小点,可以切换到指定的广告页面,也可以通过手指左右滑动来切换相邻的广告页面。效果如图1所示。
图1 广告轮询视图演示
幸运的是,小程序组件直接提供了这种效果的实现,这就是swiper组件。该组件允许水平或垂直方式暂时多个可以切换的广告页面。本节将详细介绍swiper组件的使用方法。
1. 显示水平和垂直滑动的广告页面
swiper组件有多个属性可以控制各种行为,不过最常用的当属indicator-dots属性,该属性用于控制swiper组件是否在下方或右侧显示用于控制广告页面切换的小点。默认是false,也就是不显示这些小点。
下面的布局代码设置了4个页面,用于在swiper中轮询显示。
<swiper indicator-dots="{{indicatorDots}}" >
<block wx:for-items="{{background}}" wx:key="unique">
<swiper-item>
<view class="swiper-item bc_{{item}}"></view>
</swiper-item>
</block>
</swiper>
在阅读这段布局代码时应了解如下几点。
下面是index.js中定义的几个变量。
//index.js
//获取应用实例
var app = getApp()
Page({
data: {
background: ['green', 'red', 'yellow','blue'],
indicatorDots: true,
… …
},
… …
})
显示的效果如图2所示。
图2 水平广告轮询效果
如果要让swiper组件显示垂直效果的广告轮询图,可以为swiper组件添加一个vertical属性,并将该属性值设为true(默认为false)。
<swiper indicator-dots="{{indicatorDots}}" vertical="{{vertical}}">
… …
</swiper>
现在可以在index.js文件中将vertical变量设为true,效果如图3所示。
图3 垂直广告轮询效果
在默认情况下,swiper一开始会显示第一个页面,如果想让swiper组件首先显示指定的页面,需要设置current属性(默认值是0),该属性的值表示当前显示页面的索引,从0开始。例如,下面的布局代码首先会显示第3个页面。
<swiper indicator-dots="{{indicatorDots}}" vertical="{{vertical}}" current="2">
… …
</swiper>
2 自动切换广告轮询图
对于广告轮询图来说,大多需要自动切换。也就是说,在一定时间间隔,就会从当前广告页面切换到相邻的广告页面,这样会让自己的App看着更加动态。
让swiper组件自动切换广告页面,需要设置如下几个属性。
例如,下面的布局代码设置了autoplay和interval属性。其中autoplay变量的值是true,interval变量的值是2000,也就是每2秒切换到相邻的广告页面,从第3个广告页面开始切换。切换到最后一个页面后,再从第一个页面开始切换。
<swiper indicator-dots="{{indicatorDots}}" vertical="{{vertical}}" current="2" autoplay="{{autoplay}}" interval="2000" >
… …
</swiper>
如果想让一个页面切换到另外一个页面的过程变慢(切换的时间变长),需要设置duration属性,该属性的值表示从当前页面切换到相邻页面所需要的时间,单位是毫秒,默认值是1000 。例如,使用的布局代码,相邻两个页面之间的切换需要5秒。
<swiper indicator-dots="{{indicatorDots}}" vertical="{{vertical}}" current="2" autoplay="{{true}}" interval="2000" duration="5000">
… …
</swiper>
3 响应轮询图切换事件
当页面轮询显示时,会触发页面变化事件。需要使用bindchange属性将该事件与函数绑定,例如,下面的布局代码让页面发生切换时,会调用change函数。
<swiper indicator-dots="{{indicatorDots}}" vertical="{{vertical}}" current="2" autoplay="{{true}}" interval="2000" duration="5000" bindchange="change">
… …
</swiper>
在index.js文件中需要编写如下的代码。change:function(e) { console.log(e); console.log(e.detail); // 访问e.detail.current可以获取当前页面的索引 }
其中e.detail.current可以获取当前页面的索引,如图4所示。
图 4 轮询广告时输出的日志