美文网首页
微信小程序获取滚动停止的位置

微信小程序获取滚动停止的位置

作者: 户川浪子 | 来源:发表于2019-07-10 14:26 被阅读0次

    最近有个需求需要实现获取小程序的滚动停止的位置,并触发事件。

    不能使用touchstart和touchend,因为这些是触摸事件,触摸事件完成后页面仍然会继续滑动。

    查询微信小程序官方文档得知,有个滑动事件:


    image.png

    在page对象里加入下面代码,即可获取页面滚动的位置。

    onPageScroll(res){
          console.log(res.scrollTop);
          this. getScrollTop(res.scrollTop)
    },
    

    由于只要在滚动中,就会不停地触发这个事件,而我们只需要获取它停下来时的位置,因此还需要下面的小技巧,使用setTimeOut延时执行滑动停止的代码:

    let scrollTopTimeOut;
    getScrollTop(scrollTop){
     clearTimeout(scrollTopTimeOut);
      scrollTopTimeOut = setTimeout(() =>{
        // 滑动停止的代码,此处半秒内位置不变即为滑动停止。
      }, 500);
    }
    

    获取某元素位置:

    const query = wx.createSelectorQuery().in(this)
    setTimeout(() => {
      query.select('#elementId).boundingClientRect((rect) =>{
        this.setData({
          position: rect.top
        })
      }).exec();
    }, 1000)
    

    提醒:在自定义组件内获取必须用wx.createSelectorQuery().in(this),在onReady内加入以上代码还必须加上setTimeOut延时获取,否则boundingClientRect获取到的rect值为null。

    相关文章

      网友评论

          本文标题:微信小程序获取滚动停止的位置

          本文链接:https://www.haomeiwen.com/subject/ybqhkctx.html