const { get } = require("../../utils/request")
//存放右侧分类的高度累加数组
var heightList = [];
//记录scroll-view滚动过程中距离顶部的高度
var distanceToTop = 0;
Page({
/**
* 页面的初始数据
*/
data: {
scrollList: [],//分类数据
windowHeight: '',//可视区域高度
curIndex: 0,//当前选中的分类
loading: true,//显示骨架屏
navTo: 'nav0',//右边scroll跳转至第n个scroll-item
},
// 获取分类数据
getScrollList() {
get('/api/public/v1/categories').then(res => {
// console.log(res);
this.setData({
scrollList: res.data.message
}, () => {
this.setData({
loading: false
})
this.getProListHeight()
})
})
},
// 点击左边scroll
leftScroll(e) {
let { index } = e.currentTarget.dataset
console.log(index);
this.setData({
curIndex: index,
navTo: `nav${index}`
})
},
getProListHeight() {
let tmpHeightList = [];
let tmpH = 0; //临时存放每个分类的高度
// 获取元素信息 返回一个 SelectorQuery 对象实例
const query = wx.createSelectorQuery()
query.selectAll('.scroll-right-item').boundingClientRect()
query.exec(function (res) {
// console.log(res);
res[0].forEach((item) => {
tmpH += item.height;
// Math.floor()向下取整 【根据个人需要修改】
tmpHeightList.push(Math.floor(tmpH));
})
heightList = tmpHeightList; //[386, 658, 930, 1202, ...]
// console.log(heightList);
})
},
// 滚动右边scroll
scroll(e) {
if (heightList.length == 0) return;
let scrollTop = e.detail.scrollTop; //滚动位置
let current = this.data.curIndex;
// console.log('scrollTop======>', scrollTop);
if (scrollTop > distanceToTop) {
// 超过可视区域的一半
if ((current + 1 < heightList.length) && (scrollTop >= heightList[current] - this.data.windowHeight / 2)) {
this.setData({
curIndex: current + 1
})
}
} else {
//如果右侧 可视区域的竖直滚动位置 小于 当前列表选中的项距顶部一半的高度,则更新左侧选中项
if ((current - 1 >= 0) && (scrollTop < heightList[current - 1] - this.data.windowHeight / 2)) {
this.setData({
curIndex: current - 1
})
}
}
// 更新顶部的距离
distanceToTop = scrollTop;
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let self = this
this.getScrollList()
wx.getSystemInfo({
success(res) {
self.setData({
windowHeight: res.windowHeight,
dpi: 750 / res.screenWidth
})
}
})
}
})
微信小程序scroll左右联动
于 2022-03-24 14:18:07 首次发布