小程序長內(nèi)容實(shí)現(xiàn)錨點(diǎn)效果(非srcoll-view)

小程序?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,
        });
      }
   });
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容