小程序?qū)崿F(xiàn)錨點(diǎn)一般是使用scroll-view,而srcoll-view在實(shí)現(xiàn)效果時(shí),需要指定固定的高。
遇到的項(xiàng)目中布局分為兩塊。頂部是固定,底部是長內(nèi)容,長內(nèi)容用srcoll-view動(dòng)態(tài)計(jì)算高度賦值后,onPageScroll失效(因?yàn)檎w布局其實(shí)是100%)。
為了onPageScroll不失效,長內(nèi)容不能定高,但會(huì)導(dǎo)致srcoll-view錨點(diǎn)失效。
最終實(shí)現(xiàn)方案是不使用srcoll-view來進(jìn)行錨點(diǎn)定位,而是直接計(jì)算目標(biāo)的滾動(dòng)距離,點(diǎn)擊tab頁面滾動(dòng)到目標(biāo)位置。
參考:https://blog.csdn.net/love1793912554/article/details/94289856
<block wx:for="{{tabs}}" wx:key="id" wx:for-item="item" wx:for-index="index">
<view
class="home-tab-item {{tabActive === index && 'active'}}"
data-value="{{index}}"
data-opt="{{item.id}}"
catch:tap="handleTabClick">
<view class="text"><text>{{item.label}}</text></view>
</view>
</block>
<view id="{{tab[0]}}">Basic....</view>
<view id="{{tab[1]}}">Liangdian....</view>
<view id="{{tab[2]}}">Arrounding....</view>
<view id="{{tab[3]}}">NearBy....</view>
onLoad: {
const { tabs } = this.data;
// 獲取各個(gè)錨點(diǎn)滾動(dòng)位置距離頂部的高度
tabs.map((itm) => {
query
.select("#" + itm.id)
.boundingClientRect(function (rect) {
itm.top = rect.top;
})
.exec();
});
},
data: {
tabActive: 0, // 當(dāng)前選擇的tab下標(biāo)
tabs: [
{ label: "Basic", id: "Basic" },
{ label: "Liangdian", id: "Liangdian" },
{ label: "Arrounding", id: "Arrounding" },
{ label: "NearBy", id: "NearBy" },
],
},
// 滾動(dòng)到目標(biāo)位置, tab高亮
onPageScroll:function(event) {
const { tabs } = this.data;
let curScroll = event.scrollTop;
tabs.map((itm, idx) => {
if ((idx == 0 && curScroll < tabs[idx + 1].top) || (idx == 3 && curScroll >= tabs[idx].top)) {
that.setData({
tabActive: idx,
});
return false;
}
if (curScroll > tabs[idx].top && curScroll < tabs[idx + 1].top) {
that.setData({
tabActive: idx,
});
}
});
},
// tab點(diǎn)擊滾動(dòng)到目標(biāo)位置
handleTabClick(event){
const {
value,
opt // 目標(biāo)位置id選擇器
} = event.currentTarget.dataset;
this.setData({
tabActive: value,
});
const query = wx.createSelectorQuery();
query.select("#" + opt).boundingClientRect();
query.selectViewport().scrollOffset();
query.exec((res) => {
if (res[0] && res[1]) {
// 將頁面滾動(dòng)到目標(biāo)位置
wx.pageScrollTo({
scrollTop: res[0].top + res[1].scrollTop,
duration: 300,
});
}
});
}