uniapp實現錨點跳轉


將uniapp的uni.createSelectorQuery()方法與uni.pageScrollTo(OBJECT)方法結合使用

更詳細用法見官方文檔:
uni.createSelectorQuery()方法: https://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery
uni.pageScrollTo(OBJECT)方法: https://uniapp.dcloud.io/api/ui/scroll?id=pagescrollto

核心代碼

//從當前位置到達目標位置
            uni.createSelectorQuery().select('.comment-content').boundingClientRect(data=>{//目標位置的節點:類或者id
                  uni.createSelectorQuery().select(".arc-content").boundingClientRect(res=>{//最外層盒子的節點:類或者id
                        uni.pageScrollTo({
                              duration: 100,//過渡時間
                              scrollTop:data.top - res.top  ,//到達距離頂部的top值
                        })
                  }).exec()
            }).exec();

代碼示例

<template>
      <view class="arc-content" id="arc-content">
            <view class="info-content">文章區域。。。</view>
            <view class="comment-content" id="comment-content">評論區域。。。</view>
      </view>
</template>


togglePosition(){
      if(this.positionSelect){
            this.positionSelect=false

            //從評論區域回到頂部
            uni.createSelectorQuery().select('.comment-content').boundingClientRect(data=>{//目標位置的節點:類或者id
                  uni.createSelectorQuery().select(".arc-content").boundingClientRect(res=>{//最外層盒子的節點:類或者id
                        uni.pageScrollTo({
                              duration: 100,//過渡時間
                              scrollTop:res.top - data.top  ,//返回頂部的top值
                        })
                  }).exec()
            }).exec();

      }else{
            this.positionSelect=true

            //從當前位置到達評論區域
            uni.createSelectorQuery().select('.comment-content').boundingClientRect(data=>{//目標位置的節點:類或者id
                  uni.createSelectorQuery().select(".arc-content").boundingClientRect(res=>{//最外層盒子的節點:類或者id
                        uni.pageScrollTo({
                              duration: 100,//過渡時間
                              scrollTop:data.top - res.top  ,//到達距離頂部的top值
                        })
                  }).exec()
            }).exec();
      }
},


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM