1.点击左边导航栏,右边内容滚动到指定区域
用scroll-view组件中的scroll-into-view来解决
<view class="content-group">
<view class="nav-list">
<block wx:for-items="{{list}}" wx:key="{{index}}" >
<view class="{{activeIndex == index ? 'nav-item-active':'nav-item'}}" bindtap="navClick" id="a{{item.id}}" data-id="a{{item.id}}" data-idx="{{index}}">{{item.name}}</view>
</block>
</view>
<view class="nav-content">
<scroll-view scroll-y="true" style="height: 100%;" scroll-into-view="{{contentActive}}" scroll-with-animation="true" bindscroll="onScroll">
<view class="content-items" wx:for="{{list}}" wx:key="{{index}}" id="a{{item.id}}">
<view class="content-title">{{item.name}}</view>
<view class="content-list">
<block wx:for="{{item.pages}}" wx:for-item="items" >
<view class="content-item" id="{{items.id}}" bindtap="clickview">{{items.name}}</view>
</block>
</view>
</view>
</scroll-view>
</view>
</view>
data(){
activeIndex:0,//导航栏高亮索引
contentActive:null,//内容块scroll-into-view的id
heightArr:[],//内容块高度数组
containerH:'',//窗口高度
lastActive:0,
}
给导航栏跟内容块绑定上一样的id 这样点击导航栏的时候修改scroll-into-view的值就可以滚动到指定的内容区域(注:不可绑定数字)
//点击导航栏获取到id 修改scroll-into-view的
navClick(e){
let index = e.currentTarget.dataset.idx
let id =e.currentTarget.dataset.id
this.setData({
activeIndex:index,
contentActive:id,
})
}
2.右边内容滚动 左边切换对应导航
onload(){
this.ready()
},
ready(){
var _this = this
let heightArr = []
let h = 0;
//创建节点选择器
const query = wx.createSelectorQuery();
//选择id
query.selectAll('.content-items').boundingClientRect()
query.exec(function (res) {
console.log(res,'execres')
//res就是右边所有内容盒子高度的数组
res[0].forEach((item) => {
h += item.height;
heightArr.push(h);
})
_this.setData({
heightArr: heightArr
})
})
},
监听scroll-view滚动,当scroll-view滚动的时候,就可以获取到滚动的距离,并动态计算滚动区间,判断出是右边哪个内容块的高度区间,并返回对应的索引
onScroll:function(e){
const scrollTop = e.detail.scrollTop;
const scorllArr = this.data.heightArr;
const _this = this;
if (scrollTop >= scorllArr[scorllArr.length - 1 ] - (_this.data.conHeight/2)){
return;
}else{
for(let i=0;i< scorllArr.length; i++){
if(scrollTop >= 0 && scrollTop <scorllArr[0]){
if (0 != _this.data.lastActive) {
_this.setData({
activeIndex: 0,
lastActive:0,
})
}
}else if( scrollTop >=scorllArr[i-1] && scrollTop <scorllArr[i]){
if (i != _this.data.lastActive) {
_this.setData({
activeIndex: i,
lastActive: i,
})
}
}
}
}
},