小程序利用scroll-view實(shí)現(xiàn)錨點(diǎn)功能
應(yīng)用場景:橫向tab切換時(shí),下面對(duì)應(yīng)的tab_item置頂效果(或者在一定的高度)
index.wxml:
//tab橫向?qū)Ш讲糠? <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>
//縱向內(nèi)容部分
<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
})
},
//監(jiān)聽滾動(dòng)時(shí)間 判斷高度來實(shí)現(xiàn)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:
//去掉滾動(dòng)條
::-webkit-scrollbar {
width: 0;
height: 0;
color: transparent;
}
!?。croll-view 父級(jí)一定要設(shè)置高

浙公網(wǎng)安備 33010602011771號(hào)