美文网首页
微信小程序自定义swiper组件

微信小程序自定义swiper组件

作者: Android砖家 | 来源:发表于2019-03-02 17:56 被阅读0次

    第一步:画个页面 index.wxml

    <!--index.wxml-->
    <view class="container">
      <swiper class="swipers" autoplay="{{autoplay}}" current="{{currentSwiper}}" bindchange="swiperChange">  
            <block wx:for="{{imgUrls}}" wx:key='key'>  
                <swiper-item>  
                     <image src="{{item}}" class="slide-image" bindtap='tapBanner'  data-indexurl='{{item}}' ></image>  
                </swiper-item>  
            </block>  
        </swiper>  
       <!--重置小圆点的样式  -->
        <view class="dots">  
            <block wx:for="{{imgUrls}}" wx:key="key">  
                <view class="dot{{index == currentSwiper ? ' active' : ''}}"></view>  
            </block>  
        </view>  
    </view>
    
    
    

    第二步:添加样式

    .container {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      box-sizing: border-box;
      position: relative;
      width: 100%;
      align-items: center;
    }
    
    .swipers {
      height: 562rpx;
      width: 100%;
    }
    
    .slide-image {
      width: 750rpx;
      height: 562rpx;
      display: block;
    }
    
    .dots {
      width: 156rpx;
      height: 36rpx;
      display: flex;
      flex-direction: row;
      position: absolute;
      bottom: 20rpx;
    }
    
    /*未选中时的小圆点样式 */
    
    .dot {
      width: 26rpx;
      height: 26rpx;
      border-radius: 50%;
      margin-right: 26rpx;
      background-color: white;
    }
    
    /*选中以后的小圆点样式  */
    
    .active {
      width: 26rpx;
      height: 26rpx;
      background-color: coral;
    }
    
    

    第三步: js逻辑处理

    
    //index.js
    //获取应用实例
    const app = getApp()
    
    Page({
    
      data:{
        imgUrls: [
          "https://cdn.it120.cc/apifactory/2017/09/15/145c582252a7a20f21ad9a025ae8c9be.png",
          "https://cdn.it120.cc/apifactory/2017/09/15/73560c511f554eb4afd1dcade9d8ef67.png",
          "https://cdn.it120.cc/apifactory/2017/09/15/5acdd8f65ec85b413ee642dda795d835.png"    ],
        currentSwiper: 0,
        autoplay: true
      },
    
      //滑动事件监听
      swiperChange:function(event){
        this.setData({
          currentSwiper: event.detail.current
        });
      },
    
    //banner点击事件
      tapBanner:function(event){
        //下面介绍两种banner 点击获取数据事件
        // 1. 通过数据源获取
        var indexUrl = this.data.imgUrls[this.data.currentSwiper];
        console.log(indexUrl);
        // 2 . 也可以通过自定义属性获取
        var url = event.currentTarget.dataset.indexurl;
        console.log(url);
    
      }
      
    })
    
    
    效果图:
    yhx.gif

    相关文章

      网友评论

          本文标题:微信小程序自定义swiper组件

          本文链接:https://www.haomeiwen.com/subject/julyuqtx.html