微信小程序开发(六)循环播放图制作

我们经常看到,在小程序中包含循环滚动播放的轮播图片,这是怎么做的呢,这篇文章我就带大家来完成一下,这个功能。

先来看看完成的效果图:

从效果图中,我们可以看到,有3张图轮播,点击轮播图片,当前页面还可以做出响应。

首先在项目根目录建立images文件夹,并将准备好3张图片,放在其中。具体如图:

 具体参考代码:

js文件代码:

Page({
​
  /**
   * 页面的初始数据
   */
  data: {
    imageItems: [{
      id: 1,
      imgsrc: "../../images/1.png",
      link: "http://www.test.com/id=1"
    }, {
      id: 2,
      imgsrc: "../../images/2.png",
      link: "http://www.test.com/id=2"
    }, {
      id: 15,
      imgsrc: "../../images/15.png",
      link: "http://www.test.com/id=15"
    }],
    info:""
  },
  /*点击图片事件处理函数 */
  imgTap: function (params) {
    /**
     * params代表传过来的参数集合
     * 在wxml页面是通过data-**格式传过来
     * 在js函数中通过 params.currentTarget.dataset.**方式来获取
     */
    /**在调试器控制台输出传过来参数link */
    console.info(params.currentTarget.dataset.link);
​
    /**通过小提示方式显示传过来参数id
     * 需要注意的是,title只能接受string类型值,由于id是整数,故我们需要利用+""的方法来进转换
     */
    wx.showToast({
      title: params.currentTarget.dataset.id+"",
    })
    /**下面的代码展示了如何动态设定data的值 
     * 将info的值设置为传过来参数 link
    */
    this.setData({
      info: params.currentTarget.dataset.link
    })
  }
})

 wxss文件代码:

.swiperItem {
    width: 100%;
    height: 500rpx;    
}

wxml文件代码:

<swiper class="swiperItem" indicator-dots="true" indicator-color="rgba(0,0,0,.3)" autoplay="true" 
    interval="5000" duration="1000" circular="true">
    
    <block wx:for="{{imageItems}}" wx:key="*this" wx:for-item="img">
        <swiper-item>
            <image class="swiperItem" bindtap="imgTap" data-link="{{img.link}}" data-id="{{img.id}}" src="{{img.imgsrc}}" mode="aaspectFill" lazy-load="false">             
            </image>
        </swiper-item>
    </block>
</swiper>

<text style="color:red;width:100%;height:50rpx">{{info}}</text>

微信小程序轮播图片,为我们提供了现成的组件swiper。

swiper主要属性说明:

indicator-dots:是否显示轮播指示器,即下面的小圆点

autoplay:是否自动播放

interval:各个图片切换时间间隔,单位毫秒

duration:切换耗时,单位毫秒

其他具体用法,查看文档吧,宝贝们。

https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html 

主要说明:

bindtap是绑定事件,imgTap是在js文件中做的事件响应函数

data-* * 是为了通过事件传参数,参数名即为 * *,本例传了2个参数,link与id

 

OK!轮播讲完,收! 有问题,留言!

关注我,你会获得更好的学习体验!

猜你喜欢

转载自www.cnblogs.com/lyxt/p/12564088.html