1)计算每个区间的高度
_calculateHeight(){//listHeight记录每一个节点的高度 必须所有Dom渲染完了,所以在nextTick中
let foodList=this.$refs.foodwrapper.getElementsByClassName("food-list-hook")
let height=0
this.listHeight.push(height)
for (let i = 0; i <foodList.length ; i++) {
let item=foodList[i]
height+=item.clientHeight;//clientHeight可见区域高度
this.listHeight.push(height)
}
}
需要js操作的元素,添加 -hook类,不为它添加样式,只是为了js操作
计算高度的时机,DOM元素渲染完成 this.$nextTick
this.$nextTick(()=>{
this._initScroll();
this._calculateHeight()
})
2)拿到实时的纵坐标值
data(){
return {
goods:[],
listHeight:[],
scrollY:0
}
},
better scroll的接口
this.foodScroll=new BScroll(this.$refs.foodwrapper,{
probeType:3 //该scroll在滚动的时候,可以实时获得滚动位置
})
this.foodScroll.on("scroll",(pos)=>{
this.scrollY=Math.abs(Math.round(pos.y))
})
3)scrollY和左侧做映射
用computed计算属性
computed:{
currentIndex(){//scrollY是页面滑动到的高度,看这个高度到哪里,如果位于两个高度中间,就定位到响应的序号
for (let i = 0; i <this.listHeight.length ; i++) {
let height1=this.listHeight[i]
let height2=this.listHeight[i+1]
if(!height2 || this.scrollY>=height1&&this.scrollY<height2){
return i
}
}
return 0
}
},
4)为左侧menu-item添加类
<li v-for="(item,id) in goods" class="menu-item" :class="{'current':currentIndex===id}"
@click="selectMenu(id)">