zoukankan      html  css  js  c++  java
  • 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 的子元素。

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

       完整的方法:

      

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

    
    

     

  • 相关阅读:
    react-custom-scrollbars的使用
    【react】Mobx总结以及mobx和redux区别
    【React】Redux入门 & store体验
    chrome安装react-devtools开发工具
    【vue】vuex防止数据刷新数据刷掉
    搭建博客的两个工具区别
    JavaScript中的作用域
    通过JavaScript创建表格
    JavaScript中的普通for循环和 for in循环
    JavaScript中创建默认对象的方式
  • 原文地址:https://www.cnblogs.com/jiayouba/p/14322803.html
Copyright © 2011-2022 走看看