小程序利用scroll-view实现锚点功能

应用场景:横向tab切换时,下面对应的tab_item置顶效果(或者在一定的高度)

index.wxml:
//tab横向导航部分 <scroll-view class="nav" scroll-x="true" style="height:35px;" scroll-into-view="{{leftView}}" enable-flex="true"> <view wx:for="{{tab}}" wx:key="index" class='items {{showId == index ? "active" : ""}}' data-id="{{index}}" id="T{{index}}" wx:key="{{index}}" bindtap="scrollTab">{{item}}</view> </scroll-view> //纵向内容部分 <scroll-view class="scroll" scroll-into-view="{{toView}}" scroll-y="true" scroll-with-animation="true" bindscroll="scrollTo"> <view class="menu_item" wx:for="{{list}}" id="L{{index}}" wx:key="index"> <text class="title">{{item.name}}</text> </view> </scroll-view>
index.js:
page({ data:{ showId: 0, leftView:'T0', toView: 'L0', anchorArray:[ ], }, scrollTab: function (e) { const showId = e.currentTarget.dataset.id this.setData({ showId, toView: 'L' + showId, leftView: 'T' + showId }) }, //监听滚动时间 判断高度来实现tab高亮 scrollTo: function (e) { let scrollTop = e.detail.scrollTop var _this = this let scrollArr = _this.data.anchorArray; if (scrollTop >= scrollArr[scrollArr.length - 1] - _this.data.autoHeight) { return; } else { for (let i = 0; i < scrollArr.length; i++) { if (scrollTop >= 0 && scrollTop < scrollArr[0]) { _this.setData({ showId: 0, leftView:'T'+0 }); } else if(scrollTop>=scrollArr[i-1]&&scrollTop<scrollArr[i]){ _this.setData({ showId: i, leftView:'T'+i }); } } } let query = wx.createSelectorQuery().in(_this); let heightArr = []; let h = 0; query.selectAll('.menu_item').boundingClientRect((react) => { react.forEach((res) => { h += res.height; heightArr.push(h) }) _this.setData({ anchorArray: heightArr }); }).exec(); }, })
index.wxss:
//去掉滚动条 ::-webkit-scrollbar { width: 0; height: 0; color: transparent; } !!!scroll-view 父级一定要设置高
posted @ 2023-04-19 18:37  GQMM  阅读(207)  评论(0编辑  收藏  举报