微信小程序scroll-view之左右联动
-
凡是商城类的小程序必有导航联动的模块,近期业务不忙,决定copy 一下公司app到小程序。发现这个scroll-view还是有点知识点的。记一下,以防忘记。
-
-
左边联动右边其实很简单
小程序API文档传送门(https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html?search-key=scroll-view)scroll-into-view绑定对应的ID就OK了
// 左侧 <scroll-view scroll-y="true" class="scrollViewLeft" :scroll-into-view="scrollTopId1" scroll-with-animation="true"> <block v-for="(item,index) in cgList" :key="index"> <div class="li " @click="clickLetter" :data-index="'A'+index" :class="'A'+index === scrollTopId1 ? 'active' : ''" :id="'A'+index" > {{item.categoryName}} </div> </block> </scroll-view> //右侧 <scroll-view scroll-y="true" class="scrollViewRight" :scroll-into-view="scrollTopId" scroll-with-animation="true" @scroll="onScroll" scrollTop="scrollTop"> <div class="scrollCon"> <div class="typeCon" v-for="(item,right1) in cgList" :key="right1" :id="'A'+right1"> <div class="typeImg"> <image :src="item.path" /> </div> <div class="no1Type"> <div class="no1TypeList"> <div class="no1TypeListCon" v-for="(type1,key1) in item.ranges" :key="key1"> <div class="no1Title">{{type1.categoryName}}</div> <div class="no1List"> <div class="no1ListCon" v-for="(type2,key2) in type1.ranges" :key="key2">{{type2.categoryName}}</div> </div> </div> </div> </div> </div> </div> </scroll-view>
-
而滚动右侧 联动左侧,官方文档则没有相应的api。自己动手丰衣足食。
—> 左侧导航对应右侧的子区域,只要右侧滚动到对应的区域那么,就让左侧滚动到对应到导航 -
first --> 页面加载完毕 计算右侧的高度。可以使用小程序的API(wx.createSelectorQuery();)
-
second --> 计算右侧每一块的高度 储存备用 ,怎么计算呢?小程序节点选择select 不知道的筒子们可以了解一下。
query.selectAll('.typeCon').boundingClientRect(function(n){ n.forEach((res) => { s += res.height; heightArr.push(s) }); that.heightArr = heightArr; }).exec() //注意此方法 一定要在页面加载完之后执行,否则获取不到。生命周期挨着试了,都不行,最后无奈写了个延时器。总算是得到了。
-
右侧滚动时,根据滚动高度是否在相应的区间内,联动左侧
onScroll(e){ let scrollTop = e.mp.detail.scrollTop; let scrollArr = this.heightArr; if (scrollTop >= scrollArr[scrollArr.length - 1] -this.pageHeight) { return } else { for (let i = 0; i < scrollArr.length; i++) { if (scrollTop >= 0 && scrollTop < scrollArr[0]) { this.scrollTopId1 = "A0" } else if (scrollTop >= scrollArr[i - 1] && scrollTop < scrollArr[i]) { this.scrollTopId1 = "A"+i } } } },
-
源码就不贴了。写着玩,提供个思路可以看看。有问题的筒子们,可以沟通一下。