項目需求:在頁面中,不管位於何處,點擊評論按鈕頁面滾動到對應到位置

實現思路如下:
uni.createSelectorQuery().select(".comment").boundingClientRect((res)=>{
uni.pageScrollTo({
duration:0,
scrollTop:res.top
})
}).exec();
但是你會發現,在頁面沒有滾動之前點擊評論按鈕可以直接滾動到評論,如果我頁面有滾動,滾動距離就會出現偏差
這是因為滾動到實際距離是元素距離頂部的距離減去最外層盒子的滾動距離,相關代碼如下:
uni.createSelectorQuery().select(".image-details").boundingClientRect(data=>{
uni.createSelectorQuery().select(".comment").boundingClientRect((res)=>{
uni.pageScrollTo({
duration:0,
scrollTop:res.top - data.top
})
}).exec()
}).exec();
相關鏈接:
官方獲取節點信息:https://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery
