简单实现微信小程序左右联动效果:
wxml
<view class="content">
<view class="left">
<scroll-view scroll-y="true">
<view bindtap="tabSelect" id="data{{index+1}}" class="demo1 {{index==tabCur?'select':''}}" data-index="{{index}}" wx:for="{{arrLeft}}" wx:key="*this">{{item}}</view>
</scroll-view>
</view>
<view class="right">
<scroll-view enhanced="true" show-scrollbar="true" scroll-y style="height:900rpx" scroll-into-view="{{show}}" bindscroll="getRect">
<view class='demo' id='{{item.id}}' wx:for="{{arrRight}}" wx:key="index" style='height:360rpx;background-color: cadetblue;border-bottom: 1px solid yellow;'>{{item.name}}</view>
</scroll-view>
</view>
</view>
js
Page({
/**
* 页面的初始数据
*/
data: {
arrLeft: ["demo1", "demo2", "demo3","demo4","demo5"],
arrRight: [{name:"demo1",id:"demo1"},{name:"demo2",id:"demo2"},
{name:"demo3",id:"demo3"},{name:"demo4",id:"demo4"},
{name:"demo5",id:"demo5"}],
show: '',
tabCur:0,
navList:[]
},
getRect: function (e) {
const that=this;
// console.log( e.detail.scrollTop); //回去距离顶部的距离
let j;
const arrLeft=this.data.arrLeft;
const navList=this.data.navList;
for(j=0;j<navList.length;j++){
if(e.detail.scrollTop>navList[j]&&e.detail.scrollTop<navList[j+1]){
this.setData({
tabCur:j
})
return false;
}
}
},
tabSelect: function (e) {
const arrLeft = this.data.arrLeft;
let index = e.target.dataset.index + 1;
this.setData({
show: "demo" + index,
tabCur:e.target.dataset.index
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
const that=this;
const navList=[];
this.data.arrRight.forEach(item=>{
var query = wx.createSelectorQuery();//创建节点查询器 query
query.select("#"+item.id).boundingClientRect()//选择Id=id的节点,获取节点位置信息的查询请求
query.selectViewport().scrollOffset()//获取页面滑动位置的查询请求
query.exec(function (res) {
res[0].top // #the-id节点的上边界坐标
res[1].scrollTop // 显示区域的竖直滚动位置
navList.push(res[0].top);
})
})
this.setData({
navList
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
css
.content{
display: flex;
justify-content:space-between;
}
.left{
width: 200rpx;
/* height:100rpx; */
text-align: center;
background-color: cadetblue;
text-align: center;
height: 300rpx;
}
.demo{
/* width: 400rpx;
text-align: center; */
font-size: 25px;
font-weight: 600;
}
.demo1{
height: 60rpx;
border-bottom: solid 1px yellow;
}
.right{
width: 500rpx;
text-align: center;
}
.select{
color: red;
font-weight: 600;
}