微信小程序之自定义轮播图swiper dots样式

在做微信小程序开发过程中,常用的组件就是swiper组件,通过该控件来实现轮播图效果,但是swiper组件的指示点默认是小黑点,一般情况下,我们可以根据API文档中swiper的相关属性方法进行颜色修改,如下:

indicator-color='#dbdbdb' 
indicator-active-color='#00ae61'

但是这个只能对指示点的颜色进行修改,不能满足我们开发的需要,比如我们需要指示点是方形或者椭圆形等时,官方API就不能满足我们的需求了。本文主要介绍一个实现不同需求swiper指示点的方法。
首先看下本文实现效果:

实现思路

1.禁用swiper属性indicator-dots(直接删除该属性方法)。
2.自定义view组件,实现swiper的指示点dots。

布局文件

在.wxml布局文件中添加swiper组件

<view class='swipercontent'>
  <swiper autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" current="{{swiperCurrent}}" bindchange="swiperChange">
    <block wx:for="{{imgUrls}}" wx:key="unique">
      <swiper-item>
        <image src="{{item}}" class="slide-image" width="355" height="150"/>
      </swiper-item>
    </block>
  </swiper>

  <view class="dots">
    <block wx:for="{{imgUrls}}" wx:key="unique">
      <view class="dot{{index == swiperCurrent ? ' active' : ''}}"></view>
    </block>
  </view>
</view>

在布局文件中,定义bindchange=”swiperChange”方法,用于监听swiper中item的变化,然后,定义view组件实现指示点布局。

布局属性

设置上文布局中相关组件的属性:

.swipercontent {
  position: relative;
}

swiper{
  width: 100%;
  height:340rpx;
}

swiper image {
  display: block;
  width: 100%;
  height: 100%;
}

.dots{
  position: absolute;
  left: 0;
  right: 0;
  bottom: 20rpx;
  display: flex;
  justify-content: center;
}

.dot{
  margin: 0 8rpx;
  width: 14rpx;
  height: 14rpx;
  background: #fff;
  border-radius: 8rpx;
  transition: all .6s;
}
.dot.active{
  width: 24rpx;
  background: #f80;
}

JS文件

我们通过js文件对上文中的bindchange=”swiperChange”绑定事件进行处理:

Page({
  data: {
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    autoplay: true,
    interval: 5000,
    duration: 1000,
    swiperCurrent: 0,
  },

  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  }

})

至此效果图中的效果即可实现,如有问题,欢迎留言。

猜你喜欢

转载自blog.csdn.net/lhy349/article/details/80987137