js实现页面滚动时自动切换Sidebar侧边导航标签,点击标签自动滚动页面
<van-sidebar class="sidebar" v-model="activeKey">
<van-sidebar-item :title="i.title" @click="onChange(i)" v-for="(i,k) in activeList" :key="k"/>
</van-sidebar>
<div class="filtratePopup_main">
<div class="content" ref="anchor" @scroll="handleScroll">
<div class="device_title" ref="device">设备配置</div>
<div class="item_list">
<div @click="deviceItemClick(item)" class="item van-ellipsis" v-for="(item,index) in deviceList" :key="index">{{item.equipmentName}}</div>
</div>
<div class="device_title" ref="environment">环境配置</div>
<div class="item_list">
<div @click="deviceItemClick(item)" class="item van-ellipsis" v-for="(item,index) in deviceList" :key="index">{{item.equipmentName}}</div>
</div>
<div style="height: 50vh;"></div>
</div>
方法:
methods: {
handleScroll(v){
let navList = document.querySelectorAll('.device_title')
let navTop = []
navList.forEach(i=>{
navTop.push(i.offsetTop)
})
let scroll = this.$refs.anchor.scrollTop
let index = 0
navTop.forEach((i,k)=>{
if(scroll>=i){
index = k
}
})
this.activeKey = index
},
onChange(v){
this.$refs[v.name].scrollIntoView({ behavior: 'smooth' })
},
注意的点:
1、如果最后一个内容过少,可能会出现点击最后一个,Sidebar导航定位到上面的问题,需要看情况加上底部内容
2、因为监听 会有所卡顿