ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] #### BScroll 制作左右联动导航 1. 图例 ![](https://box.kancloud.cn/94e9f1275e82a1337d1d8a261b9b48a3_373x506.png) 2. 需求: * [ ] 点击左侧菜单 右侧滚动到对应位置 * [ ] 滚动右侧菜单 左侧跟随联动 3. 实现步骤 * [ ] 监听右侧商品列表滚动Y坐标 scrollY = 0 * [ ] 求出右边商品列表累加的所有高度,存放在一个数组中 goodsList = [] * [ ] 利用计算属性,计算出 scrollY 定位在 goodsList 数组中的区间值 >[danger] 每当监听到scrollY 值改变,计算属性会重新计算,返回最新区间值 * [ ] 公式: ~~~ computed: { ...mapState({ goodsData: state => state.goodsData }), currentIndex() { return this.listHeight.findIndex((item, index) => { return !this.listHeight[index+1] || (this.scrollY >= item && this.scrollY < this.listHeight[index+1]) }) } }, ~~~ * [ ] 点击左侧按钮,右侧商品列表滚动到对应位置 核心算法: ~~~ scrollTo(index) { const goodsListEl = Array.from(this.$refs.goodsList.querySelectorAll('li')) this.listScroll.scrollToElement(goodsListEl[index], 300) } ~~~ * [ ] 右侧滚动,左侧联动 思考: 要触发左侧菜单导航联动,需要在滚动左侧菜单时,拿到对应索引,然后用scrollToElement 跳转到对应的位置 核心算法: ~~~ // 监听滚动事件 this.listScroll.on('scroll', (pos) => { const posY = Math.round( Math.abs(pos.y) ) this.scrollY = posY this.scrollMenu(this.currentIndex); }) ~~~ ~~~ scrollMenu(index) { const menuList = Array.from(this.$refs.goodsMenu.querySelectorAll('li')); this.menuScroll.scrollToElement(menuList[index], 300, false, -320) } ~~~ >[danger] 注意: this.scrollY 滚动时改变数据,会触发计算属性重新计算,然后根据计算属性返回的索引值来跳转对应的菜单导航