在商品列表页面里,左边是商品分类,右边是商品列表二个scroll-view 互相联动,
var heightList = []; //存放右侧分类的高度累加数组
var distanceToTop = 0; //记录scroll-view滚动过程中距离顶部的高度
var scrollRightCount = 0;
var scrollRightItemHeight = 30; //右边item高度 滚动右边时累加左边值
Page({
/**
* 页面的初始数据
*/
data: {
classify: [
],
windowHeight: '',//可视区域高度
curClassIndex: 0,//当前选中的分类
navToRight: 'nav0',//右边scroll跳转至第n个scroll-item
scrollRight: 0,
},
onClassChange(event) {
let { detail } = event
let index = event.detail
console.log("index=", index, "detail=", detail);
this.setData({
curClassIndex: index,
navToRight: `nav${index}`
})
},
onLeftScroll(e) {
scrollRightCount = e.detail.scrollTop; //滚动位置
},
// 滚动右边scroll
onRightScroll(e) {
if (heightList.length == 0) return;
let scrollTop = e.detail.scrollTop; //滚动位置
let current = this.data.curClassIndex;
if (scrollTop > distanceToTop) {
if ((current + 1 < heightList.length) && (scrollTop >= heightList[current])) {
this.setData({
curClassIndex: current + 1
})
}
} else {
if ((current - 1 >= 0) && (scrollTop < heightList[current - 1])) {
this.setData({
curClassIndex: current - 1
})
}
}
if (current > (heightList.length / 3) && scrollRightCount < this.data.windowHeight / 3) {
scrollRightCount = scrollRightCount + scrollRightItemHeight
this.setData({
scrollRight: scrollRightCount
});
}
else if (scrollRightCount >= scrollRightItemHeight) {
scrollRightCount = scrollRightCount - scrollRightItemHeight
if (scrollRightCount <= 0)
scrollRightCount = 0;
this.setData({
scrollRight: scrollRightCount
});
}
// 更新顶部的距离
distanceToTop = scrollTop;
},
//获取右边每个item高度数组
getRightItemHeight() {
heightList = [];
let tmpH = 0;
// 获取元素信息 返回一个 SelectorQuery 对象实例
const query = wx.createSelectorQuery()
query.selectAll('.scroll-right-item').boundingClientRect()
query.exec(function (res) {
res[0].forEach((item) => {
tmpH += item.height;
heightList.push(Math.floor(tmpH));
})
console.log(heightList);
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
var systemInfo = wx.getSystemInfoSync();
this.setData({
headHeight: systemInfo.windowHeight - 100,
windowHeight: systemInfo.windowHeight
});
var classify = [];
for (var i = 0; i < 50; i++) {
classify.push({
id: "class" + i,
name: "标签:" + i,
selected: false
});
}
this.setData({
classify: classify
});
this.getRightItemHeight();
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})