效果
1.点击tab页跳转至当前锚点内容
2.滚动页面时标签自动切换至当前tab
实现
1.wxml
使用scroll-view组件,顶部和内容都设成可滚动的区域
extraHeight是接下来要计算的额外高度,作用是点击到最后一个tab页时,内容可以在顶部
<view class="container">
<scroll-view scroll-x class="nav" scroll-with-animation scroll-left="{{scrollLeft}}">
<view class="cu-item {{index==TabCur?'cur':''}}" wx:for="{{tabs}}" wx:key="{{index}}" bindtap="tabSelect"
data-id="{{item.id}}">
{{item.name}}
</view>
</scroll-view>
<scroll-view scroll-y scroll-into-view="{{toView}}" class="scroll" scroll-with-animation="{{true}}"
bindscroll="handelScroll">
<block wx:for="{{tabs}}" wx:key="{{index}}">
<classify-icon class="mg-top" id="L{{index}}" title="{{item.name}}" list="{{list}}"></classify-icon>
</block>
<view style="height :{{extraHeight}}px"></view>
</scroll-view>
</view>
2.实现点击tab页跳转内容
scroll-view组件有一个属性是scroll-into-view,可以实现锚点效果
用法:
- 在要跳转的内容上加id元素
<classify-icon class="mg-top" id="L{{index}}" title="{{item.name}}" list="{{list}}"></classify-icon>
-
初始化toView属性,设置scroll-into-view=”{
{toView}}”
toView: 'L0', //卡片初始锚点
<scroll-view scroll-y scroll-into-view="{{toView}}" class="scroll" scroll-with-animation="{{true}}"
- 点击tab页事件,设置点击项、偏移量和锚点
tabSelect(e) {
let id = e.currentTarget.dataset.id;
this.setData({
TabCur: id,
scrollLeft: (id - 1) * 84,
toView: 'L' + id
})
},
3.实现滚动页面自动切换tab
- 初始化高度
onShow: function () {
// 计算滚动区域的高度
wx.createSelectorQuery().select('.scroll').boundingClientRect(rect => {
this.setData({
scrollHeight: rect.height,
})
}).exec();
let tabs = this.data.tabs;
let tabHeight = 0;
let extraHeight = 0;
// 获取每个tab对应的锚点元素,计算元素的top和bottom高度
for (let i = 0; i < tabs.length; i++) {
let view = wx.createSelectorQuery().select("#L" + tabs[i].id);
view.fields({ size: true }, data => {
tabs[i].top = tabHeight;
tabHeight = tabHeight + data.height;
tabs[i].bottom = tabHeight;
if (i == tabs.length - 1) {
// 计算最后一个元素的额外高度
extraHeight = this.data.scrollHeight - data.height;
this.setData({
extraHeight,
tabs: tabs
})
}
}).exec();
}
},
- 监听内容滚动事件,根据当前scrollTop判断页面滚动到tabs的索引
handelScroll(e) {
let scrollTop = e.detail.scrollTop;
let tabs = this.data.tabs;
for (let i = 0; i < tabs.length; i++) {
if (scrollTop > tabs[i].top && scrollTop < tabs[i].bottom) {
this.setData({
scrollLeft: (tabs[i].id - 1) * 84,
TabCur: tabs[i].id
})
return false
}
}
}
4.wxss
.container {
padding: 20rpx 40rpx;
}
.mg-top {
margin-top: 30rpx;
}
.nav {
white-space: nowrap;
margin-bottom: 20rpx;
}
::-webkit-scrollbar {
display: none;
}
.nav .cu-item {
height: 90rpx;
display: inline-block;
line-height: 90rpx;
margin: 0 10rpx;
padding: 0 20rpx;
}
.nav .cu-item.cur {
border-bottom: 4rpx solid;
color: #0C84FE;
}
.scroll {
height: 88vh;
}
版权声明:本文为yang_da_da原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。