效果
wxml
<view class='box'>
<scroll-view scroll-y scroll-with-animation style="width:25%">
<view class='nav'>
<view wx:for="{{navList}}" wx:key='index' class="title {{index == active ?'select':''}}"
data-index='{{index}}' bindtap='activeNav'>{{item}}</view>
</view>
</scroll-view>
<scroll-view scroll-y style="width:75%" scroll-with-animation scroll-into-view="{{selectId}}"
bindscroll="watchScroll">
<view class='content'>
<view id='{{"item"+index}}' class='subtitle' wx:for="{{navList}}" wx:key='index'>{{item}}</view>
</view>
</scroll-view>
</view>
css
.box {
display: flex;
}
.nav {
height: 100%;
width: 100%;
background: #F5F5F5;
box-sizing: border-box;
flex-wrap: wrap;
}
.title {
box-sizing: border-box;
width: 100%;
padding: 32rpx;
font-size: 28rpx;
}
.select {
background: #fff;
border-left: 5rpx solid #eec718;
box-sizing: border-box;
}
.content {
padding: 0 30rpx;
box-sizing: border-box;
width: 100%;
height: 100vh;
}
.subtitle {
width: 100%;
height: 650rpx;
border-bottom: 10rpx #f5f5f5 solid;
}
js
Page({
data: {
heightArr: [],
distance: 0,
active: 0,
selectId: "item0",
navList: ['全部甜品', '今日甜品系列', '毛巾卷系列', '切块系列', '限时限量系列', '提拉米苏系列']
},
onLoad: function (options) {
this.selectHeight();
},
// 选择左侧标签锚点定位
activeNav(e) {
var index = e.currentTarget.dataset.index
this.setData({
active: index,
selectId: "item" + index
})
},
//计算右侧每个锚点的高度
selectHeight() {
var list = []
var height = 0;
const query = wx.createSelectorQuery();
query.selectAll('.subtitle').boundingClientRect()
query.exec((res) => {
res[0].forEach((item) => {
height += item.height;
list.push(height)
})
this.data.heightArr = list
})
},
//监听scroll-view的滚动事件
watchScroll(e) {
let scrollTop = e.detail.scrollTop; //获取距离顶部的距离
let active = this.data.active;
if (scrollTop >= this.data.distance) {
if (active + 1 < this.data.heightArr.length && scrollTop >= this.data.heightArr[active]) {
this.setData({
active: active + 1
})
}
} else {
if (active - 1 >= 0 && scrollTop < this.data.heightArr[active - 1]) {
this.setData({
active: active - 1
})
}
}
this.data.distance = scrollTop;
}
})