每天一点点之 uni-app 框架开发 - 页面滚动到指定位置

项目需求:在页面中,不管位于何处,点击评论按钮页面滚动到对应到位置

实现思路如下:

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

猜你喜欢

转载自www.cnblogs.com/cap-rq/p/11006807.html