將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();
}
},