一、效果:
当页面滑动至顶部,这个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导航居中+滚动顶部吸顶效果,成功的留个言吧~