1. 程式人生 > >微信小程式之自定義輪播圖swiper dots樣式

微信小程式之自定義輪播圖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
    })
  }

})

至此效果圖中的效果即可實現,如有問題,歡迎留言。