微信小程序顶部滑动选项的简单实现

1.wxml代码块
<view class="swiper_tab_view">

    <scroll-view scroll-x='true' scroll-left="{{navleft}}" class='tab-h' scroll-with-animation="true">

      <view data-current="{{index}}" class="swiper-tab-list {{currentTab == index ? 'on' : ''}}" wx:for="{{titles}}" wx:key="key" bindtap="swichNav">{{item.title}} </view>

    </scroll-view>

  </view>

<swiper current="{{currentTab}}" class="swiper-box" duration="500" style="height:{{winHeight - 57}}px" bindchange="bindChange">

<<swiper-item>

    <view>视频</view>

  </swiper-item>

  <swiper-item>

    <view>推荐</view>

  </swiper-item>

  <swiper-item>

    <view>上海</view>

  </swiper-item>

<swiper-item>

    <view>娱乐</view>

  </swiper-item>

  <swiper-item>

    <view>体育</view>

  </swiper-item>>

  </swiper>

</view>

2.css的代码

.page{

  width: 100%;

  height: 100%;

}

.content{

  width: 100%;

  height: 100%;

}

.tab-h{

  height: 57rpx;

  width: 100%;

  line-height: 51rpx;

  background: white;

  font-size: 16px;

  white-space: nowrap;

  z-index: 999;

  margin-top: 20rpx;

}

.swiper_tab_view{

  width: 100%;

  text-align: center;

  line-height: 80rpx;

}

.swiper-tab-list {

  font-size: 30rpx;

  display: inline-block;

  width: 20%;

  color: #777;

}

.on {

  color: #da7c0c;

  border-bottom: 5rpx solid #da7c0c;

}

.swiper-box {

  display: block;

  overflow: hidden;

  height: 100%;

}

.swiper-box view {

  text-align: left;

}

3.js的代码

data: {

    titles:[

      {

        title:'视频'

      },

      {

        title:'推荐'

      },

      {

        title:'上海'

      },

      {

        title:'娱乐'

      },

      {

        title:'体育'

      }

    ],

    currentTab: 0,//当前点击的选项卡下标

    navleft:0,//需要选项卡左移的位置距离

    winWidth: wx.getSystemInfoSync().windowWidth,

    winHeight: wx.getSystemInfoSync().windowHeight,

  },

swichNav:function(e){

    let cur = e.target.dataset.current //获取当前点击的下标

    let width = wx.getSystemInfoSync().windowWidth

    let left =  (cur - 2)*width/5//计算出居中所需要的偏移量

    if ( cur != this.data.currentTab) {//如果点击了其他选项卡则进行偏移,改变颜色

      this.setData({

        currentTab:cur,

        navleft:left

      })

    }

  },

  bindChange: function (e) {

    var that = this;

    let width = that.data.winWidth

    let left =  (e.detail.current - 2)*width/5

     that.setData({

      currentTab: e.detail.current,

      navleft:left

    });

      this.checkCor();

  },

  checkCor:function(){

    if(this.data.currentTab>4){

      this.setData({

        scrollleft:300

      })

    }else{

      this.setData({

        scrollleft:0

      })

    }

  },

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。