uniapp 滚动到指定元素的位置 滚动到底部、顶部 uni.pageScrollTo失效

前言:

  大概有两种方式,一种是使用 uni.pageScrollTo 方法;

  另一种是使用  scroll-view 标签的属性:scroll-top(距离值 num) 或 scroll-into-view(子元素的id,不能以数字开头 string);

  两种方式的前提是:提供具体的高度值(scroll-view 也可以横向滚动到指定位置)。

 

一、uni.pageScrollTo 

  uni.pageScrollTo 不起效果的原因可能有两: 1,值格式不对;2,布局格式不对。

     如果是传入  selector  不起效

uni.pageScrollTo({
    duration: 300,
    selector: id // string 选择器
});

   应该是 id 格式不支持纯数字,其实类名之类的最好不要用数字,实在要用,使用单词加数字后缀。

   如果传入  scrollTop  不起效:

uni.pageScrollTo({
    duration: 300,
    scrollTop: top // number number number!
});

   那么应该是布局的问题, 它是页面级的滚动:所有的 滚动单元 必须是在根元素下,由 滚动单元 直接撑起来的高度,就可以滚动到指定位置

   不能内嵌到深层里面去,我布局比较喜欢来一个 container ,然后包含 title、content、 pop...之类的,滚动内容全在 content 里面,这样子是不起效果的,滚不动,需要是 container 的子元素。

  官网的截图,可能是改了值类型没更新:

   完整的方法:

  

1
2
3
4
5
6
7
8
 uni.createSelectorQuery().select(".cci-end").boundingClientRect((res)=>{
      console.log(res)
      const scrollH = res.top;
  uni.pageScrollTo({
    duration: 100,// 过渡时间
    scrollTop: scrollH,// 滚动的实际距离
  })
}).exec()

  

二、scroll-view 标签

<scroll-view class="container-chat-items" scroll-y :scroll-top='scrollTop' :style="{height: msgHeight + 'px'}">
            
        </scroll-view>

  使用这个没发现啥问题,直接随时修改 scrollTop 的值就可以滚动,在需要使用 scroll-view 的地方直接用。

 

最后: 

    获取元素的信息都是使用 

      uni.createSelectorQuery().select(".cci-end").boundingClientRect((res)=>{
                console.log(res)
          }).exec()

 注: 需要在生命周期 mounted 后进行调用。

      建议可以在需要的位置使用一个 高度 0 的标签标记 ID 来定位。

自定义组件编译模式(默认模式),需要使用到 selectorQuery.in 方法,包装下:

复制代码

Vue.prototype.$getRect = function(selector) {
  return new Promise(resolve => {
    uni.createSelectorQuery()
    .in(this)['select'](selector)
    .boundingClientRect(rect => {
      if (rect) {
        resolve(rect);
      } else {
        resolve('no info');
      }
    })
    .exec();
  });
}


复制代码

 

 

 

posted @   飞叶飞花  阅读(30248)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示