0
点赞
收藏
分享

微信扫一扫

微信小程序锚点选择导航栏

云上笔记 2022-07-12 阅读 45


微信小程序锚点选择导航栏_f5

<view class='box'>
<scroll-view scroll-y scroll-with-animationstyle="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-ystyle="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>

.box {
display: flex;
}

.nav {
height: 100vh;
width: 100%;
background: #F5F5F5;
display: flex;
flex-direction: column;
}

.title {
width: 100%;
height: 120rpx;
line-height: 120rpx;
text-align: center;
}

.select {
background: #fff;
border-left: 5rpx solid #16BA98;
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;
}

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;
}
})


举报

相关推荐

0 条评论