小程序scroll-view和swiper结合使用,实现标签功能(完美版)

微信小程序为了实现scroll-view配合swiper实现tab栏切换 动态的渲染scroll-view 滑动swiper scroll-view滚动到相对应的地方,网上找了很多资料,但都不尽人意,小白试了进一天,终于找到答案,闲话不多说,直接上代码。

代码:


##wxss

.top_bottomView {
  display: flex;
  border-bottom: 4rpx solid #f5f5f5;
}

.scroll-x {
  height: 78rpx;
  width: 88%;
  white-space: nowrap;
  box-sizing: border-box;
  overflow: hidden;
}
/* 隐藏scrollbar */
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}

.view-inline{
  width: 17.2%;
  height: 100%;
  display: inline-block;
}

.view-item {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  font-size: 32rpx;
  opacity: 0.6;
}
.item-active {
  opacity: 1;
  font-size: 36rpx;
}

.top_rightView {
  width: 12%;
  height: 78rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.top_rightImage {
  height: 32rpx;
  width: 32rpx;
}```



## wxml
<view class='top_bottomView'>
  <scroll-view scroll-x class="scroll-x" scroll-left="{{navScrollLeft}}" scroll-with-animation="{{true}}">
    <block wx:for="{{list}}" wx:key="index">
      <view class="view-inline">
        <view class="view-item {{clickNumber==index?'item-active':''}}" data-current="{{index}}" bindtap='onCenterTap'>
          {{item}}
        </view>
      </view>
    </block>
  </scroll-view>
  <view class='top_rightView'>
    <image src='../../JXY_icon/down.png' class='top_rightImage'></image>
  </view>
</view>
<!-- 内容区 -->
<swiper style="width: {{width*2}}rpx" bindchange='onChangeSwipeTap' duration="300" current='{{clickNumber}}'>
  <swiper-item wx:for="{{list}}" wx:key="index">
    <view class='test-class'>{{list[index]}}</view>
  </swiper-item>
</swiper>```




## js
data: {
    list: ['关注', '推荐', '游戏', '新闻', '体育', '电影', '电视', '综艺', '少儿', '音乐', '网易', '电商', '微商', '热卖'],
    clickNumber: 0,
  },

  updateSelectedPage: function(current) {
    var current = current;
    var itemWidth = this.data.itemWidth;//一个标签的宽度
    var activeWidth = (current-3) * itemWidth;//重点:重新定义固定轮播点(指定哪个位置轮播)
    this.setData({
      navScrollLeft: activeWidth,
      clickNumber: current,
    })
  },

  //点击上方文字  切换
  onCenterTap: function(event) {
    console.log(event);
    var current = event.target.dataset.current;
    this.updateSelectedPage(current);
  },

  // 滚动切换标签样式
  onChangeSwipeTap: function(event) {
    console.log(event);
    var current = event.detail.current;
    this.updateSelectedPage(current);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var height = wx.getSystemInfoSync().windowHeight;
    var width = wx.getSystemInfoSync().windowWidth;
    var itemWidth = width * 0.172*0.88;//对应wxss
    this.setData({
      height: height,
      width: width,
      itemWidth: itemWidth
    })
  },```


有问题的可以跟我分享交流哦。。。

你可能感兴趣的:(小程序scroll-view和swiper结合使用,实现标签功能(完美版))