主要利用了scroll-view里面的属性
一.首先是静态布局
<template>
<view class="ld">
<view class="left">
<view v-for="(item,index) in list" :key="index"
:class="{active:currentIndex==index}"
@click="changeactive(index)">{{item.title}}</view>
</view>
<view class="right">
<scroll-view scroll-y="true"
style="height: 200px;"
:scroll-into-view="doms"
scroll-with-animation
@scroll="scrolls"
@scrolltolower="scrolltolower">
<view v-for="(items,index) in list" :key="index" :id="'po'+index" class="title">
<view class="titlecolor">{{items.title}}</view>
<view v-for="(it,index) in items.list" :key="index">{{it}}</view>
</view>
</scroll-view>
</view>
</view>
二.script中的内容
export default {
data() {
return {
list:[
{title:"中餐",list:['盖饭','扒饭','鸡骨头','鸡肉']},
{title:"西餐",list:['牛排','羊排','鸡排','猪排']},
{title:"南餐",list:['胡萝卜','青椒','炒鸡蛋','西虹市']},
{title:"北餐",list:['锅包肉','肉包','杀猪菜','血肠']}
],
currentIndex:0,
doms:'',
topList:[]
}
},
onLoad() {
},
onReady(){
this.getNodesInfo()
},
methods: {
scrolltolower(){
setTimeout(()=>{
this.currentIndex =3
},80)
},
scrolls(e){
let scrollTop = e.target.scrollTop
for(let i =0;i<this.topList.length;i++){
let h1 = this.topList[i]
let h2 = this.topList[i+1]
if(scrollTop>=h1&&scrollTop<h2){
this.currentIndex = i
}
}
},
getNodesInfo(){
const query = uni.createSelectorQuery().in(this);
query.selectAll('.title').boundingClientRect().exec((res)=>{
let nodes = res[0]
let rel =[];
nodes.map(item=>{
rel.push(item.top)
})
this.topList =rel
})
},
changeactive(index){
this.currentIndex =index
this.doms = 'po'+index
}
}
}
三.css样式
<style lang="less">
.ld{
display: flex;
.left{
width: 100px;
border: 1px solid red;
}
.right{
flex: 1;
}
}
.active{
background-color:#007aff ;
}
.titlecolor{
background-color: red;
}
解析:
scroll-y是为了能在Y轴上进行滚动
scroll-into-view先等于一个doms空字符串,然后给右边的每个页面自定义属性一个id,id名字就是po+index,给左边的demo一个点击事件,index也要传过去,然后就通过赋值给doms,点击哪个就对应哪个,实现锚点跳转
scroll-with-animation是为了让他跳转的时候不僵硬,有一个动画效果
@scroll="scrolls"是让右边滚动的时候左边的demo也对应,主要通过渲染页面完成时,在onReady中调用一个获取高度的函数,当滚动的高度在取的两个高度之间的时候,就把currentIndex赋上值
@scrolltolower="scrolltolower"作用是,时常滚动到最后一个时候,监听就没效果,这个时候就给他一个定时器,把左边的最后一个demo的下标赋给currentIndex就可以了