【已解决】微信小程序tab导航居中+滚动顶部吸顶效果

一、效果:
当页面滑动至顶部,这个tab导航条会固定在顶部,实现吸顶的效果
在这里插入图片描述
二、代码:
wxml:

<scroll-view class="tab stickyClass" scroll-x scroll-left="{{tabScroll}}" scroll-with-animation="true">
  <block wx:for="{{menuList}}" wx:key="index">
    <view class="tab-item {{currentTab == index ? 'active' : ''}}" data-current="{{index}}" bindtap='clickMenu' data-typeid='{{item.id}}'>{{item.field}}</view>
  </block>
</scroll-view>

js:

//测试数据
data:{
 	tabScroll: 0, //使得导航位置居中
    currentTab: 0,  //当前的分类tab
    currentTypeid: 0, //当前的分类的id
    menuList: [{id: 0, field: "所有"},
    		  {id: 1, field: "官方商品"},
    		  {id: 2, field: "手机电脑"},
    		  {id: 3, field: "游戏交易"}] //导航栏菜单列表
},
//单击导航栏
clickMenu: function(e) {
  var current = e.currentTarget.dataset.current //获取当前tab的index
  var tabWidth = this.data.windowWidth / 5 // 导航tab共5个,获取一个的宽度
  var typeid = e.currentTarget.dataset.typeid; //获取当前的类型id

  this.setData({
    tabScroll: (current - 2) * tabWidth, //使点击的tab始终在居中位置
    currentTypeid: typeid,
    currentTab: current
  })
}

css:
//核心css样式, position: sticky

//核心
.stickyClass{
    position: sticky ;
    top: 70rpx; //距离顶部还有多少时候产生吸顶效果
    z-index: 9999;
}
.tab {
  width: 100%;
  margin-top: 10rpx;
  top: 0;
  left: 0;
  z-index: 100;
  white-space: nowrap;
  box-sizing: border-box;
  overflow: hidden;
  line-height: 70rpx;
  background: white;
  border-bottom: 2rpx solid #f5f5f5;
  padding-left: 3%;
  padding-right: 3%;
}

.tab-item {
  display: inline-block;
  text-align: center;
  font-size: 30rpx;
  padding-left: 25rpx;
  padding-right: 25rpx;
  z-index: 999;
}

.active {
  border-bottom: 5rpx solid #ef696c;
  color: #ef696c;
}

.active1 {
  background: #ef696c;
}

综上,即可实现tab导航居中+滚动顶部吸顶效果,成功的留个言吧~

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值