小程序实现tab+swiper联动完整代码

实现思路

1.利用swiper的bindchange方法,匹配tab下标,从而对应tab下的swiper-item内容
2.获取每个tab的left值,及下划线元素的数据

wxml部分:



  {{item}}
  



  
    1111111
  
  
    222222
  
  
    333
  

js部分:

Page({
  data: {
    tabnav: ['第一个签', '第二个签', '第三个签'],
    showtab: 0, //顶部选项卡索引
    currentTab: 0, //swiper索引
    tabInfo: ''
  },
  // tab点击
  tabClick(e) {
    let { tabindex } = e.currentTarget.dataset
    this.setData({
      showtab: tabindex
    })
    if (this.data.currentTab === tabindex) {
      return false
    } else {
      this.setData({
        currentTab: tabindex
      })
    }
  },
  // swiper滑动
  bindChange(e) {
    let { current } = e.detail
    this.setData({
      currentTab: current,
      showtab: current,
    })
  },
  onLoad() {
    let query = wx.createSelectorQuery();
    // 获取tab数据
    query.selectAll('.tab-item').boundingClientRect(rect => {
      this.setData({
        tabInfo: rect
      })
    }).exec()
    // 获取下划线数据
    query.select('.tab-line').boundingClientRect(rect => {
      this.setData({
        tabLineInfo: rect
      })
    }).exec()
  },
})

css部分

.tab {
  position: absolute;
  display: flex;
  width: 100%;
  justify-content: center;
  color: #BBBBBB;
  font-size: 28rpx;
  font-weight: 700;
}

.tab view:not(:last-child) {
  margin-right: 30rpx;
}

.tabActive {
  color: #000 !important;
}

.tab-line {
  position: absolute;
  background-color: #C6FDB2;
  width: 61rpx;
  height: 6rpx;
  border-radius: 30rpx;
  bottom: -10rpx;
  left: 0;
  transition: all 0.3s;
}
.swiper-box {
  width: 100%;
  position: absolute;
  margin-top: 146rpx;
  text-align: center;
}
附带代码片断调试 https://developers.weixin.qq.com/s/vM0PUQm27rD7

更多相关内容关注:bug纪念录

你可能感兴趣的:(小程序实现tab+swiper联动完整代码)