本文实现了微信小程序的悬浮tab标签布局,当页面向上滚动到tab标签布局时,标签布局置顶。

    效果图如下所示:

show

    本文基于mpvue项目框架,注意安装完成之后还需添加scss的支持:

npm install sass-loader node-sass

    tab标签布局悬浮置顶的核心思想是判断占位图布局A和列表布局B:当A布局向上滚动到不可见而B布局仍处于可见状态时改变tab标签布局css样式,将其置顶;否则的话取消tab标签布局的置顶样式。微信小程序有提供相关的回调方法:

wx.createIntersectionObserver()
    .relativeToViewport()
    .observe('.occupy-div', res => {
    // 控件本身与显示区域相交区域占目标节点的布局区域的比例
    this.intersection = res.intersectionRatio !== 0
})
wx.createIntersectionObserver()
    .relativeToViewport()
    .observe('.list', res => {
    // 控件本身与显示区域相交区域占目标节点的布局区域的比例
    this.listDisplay = res.intersectionRatio !== 0
})

    tab标签布局采用横向的scroll-view实现:

  <div class="container">
    <scroll-view scroll-x="true" class="scroll-view" :scroll-into-view="toView" scroll-with-animation="true">
      <div class="tab-container" v-for="(item, index) in tags" :key="item.id">
        <div :class="{'selected': selectIndex === index}" @click="tagClick(index)" class="normal" :id="'A' + item.id" >
          {{item.tag_name}}
        </div>
        <div class="indicator" v-if="selectIndex === index"></div>
      </div>
    </scroll-view>
  </div> 

    对应点击标签自动滚动的问题的实现:当点击前两个标签时总是滚动到index为0的标签,否则的话向左滚动两个标签:

  selectTag(index = 0) {
    this.tagSelectIndex = index
    if (index < this.tagList.length) {
      this.tagSelectID = this.tagList[index].id
      if (this.tagSelectIndex < index) {
        this.tagName = 'A' + this.tagList[index].id
      } else {
        if (index >= 2) {
          this.tagName = 'A' + this.tagList[index - 2].id
        } else {
          this.tagName = 'A' + this.tagList[0].id
        }
      }
    }
  }

    源码传送门:https://github.com/tianyalu/mpvue-float-tab

Logo

前往低代码交流专区

更多推荐