uni-app技巧:让你的页面轻松跳转到指定位置(锚点实现)
最编程
2024-08-02 14:53:50
...
一、页面滚动到指定位置(即实现锚点的功能)
项目需求:在页面中,不管位于何处,点击评论按钮页面滚动到对应的评论位置。
解决方案:将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").boundingClientRect((res)=>{
uni.pageScrollTo({
duration:0,
scrollTop:res.top
})
}).exec();
但是你会发现,在页面没有滚动之前点击评论按钮可以直接滚动到评论,如果我页面有滚动,滚动距离就会出现偏差。
这是因为滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离。
最终实现代码如下:
toComment () {
uni.createSelectorQuery().select('.article-box').boundingClientRect(data => {
uni.createSelectorQuery().select('#Comment').boundingClientRect(res => {
uni.pageScrollTo({
scrollTop: res.top - data.top - 10
})
}).exec()
}).exec()
}
原文地址:https://www.cnblogs.com/goloving/p/14257964.html
上一篇: 如何在 Fabric 中添加组织锚节点?