微信小程序自定义指示器(简单易上手)

image.png

1、绑定轮播事件

在wxml绑定事件:

<swiper ... bindchange="swiperFn">
    ...
</swiper>

在js中写事件:

Page({
  ...
  swiperFn(e){
    console.log(e.detail.current);  // 通过事件对象,可以打印出来当前值,表示当前为第几张图
  }
})

2、删除多余属性

wxml中,将 swiper 标签上的 indicator-dots="{{indicatorDots}}" 属性删掉,将js中data里的 indicatorDots: true, 属性删掉。

因为我们打算自定义指示器,因此这两处没有存在的必要。

3、增加指示器

wxml中:

<view class="page-section page-section-spacing swiper">
  <view class="indicator">
    <view wx:for="{{background}}" wx:key="*this" class="{{index==swiperNum ? 'active' : ''}}">          </view>
    </view>
</view>
以上的 class="{{index==swiperNum ? 'active' : ''}}" 是三元运算符写法。

wxss中:

.swiper, swiper, swiper image{
  width: 100%;
  height: 500rpx;
  display: block;
}

.swiper{
  position: relative;
}

.indicator{
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
}

.indicator view{
  width: 30rpx;
  height: 30rpx;
  background: #ccc;
  border-radius: 30rpx;
  float: left;
  margin-left: 20rpx;
  transition: all 1s linear;
}

.indicator view.active{
  width: 50rpx;
  background: #34399C;
}

js中:

Page({
  data: {
    ...
    autoplay: true,
    swiperNum: 0
  },
  swiperFn(e){
    this.setData({
      swiperNum: e.detail.current
    })
  }
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容