[微信小程序]wx.createSelectorQuery()获取页面或组件中界面上的节点信息

1、 官网例子----wx.createSelectorQuery()

微信小程序-wx.createSelectorQuery()——获取页面中界面上的节点信息上的是在Page中获取的
在这里插入图片描述

const query = wx.createSelectorQuery()
query.select('#the-id').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(function(res){
    
    
  res[0].top       // #the-id节点的上边界坐标
  res[1].scrollTop // 显示区域的竖直滚动位置
})

2、在Component中获取界面节点信息

在这里插入图片描述
我在用colorUI中的verticalNav时,发现其中一段代码我用了之后有问题,
这个方法是绑定在右边scroll-view的bindscroll的,主要作用是取到右边模块的宽度高度,从而设置右边scroll-view 的scroll-top属性(设置竖向滚动条位置)

VerticalMain(e) {
    
    
    let that = this;
    let list = this.data.list;
    let tabHeight = 0;
    if (this.data.load) {
    
    
      console.log(list)
      for (let i = 0; i < list.length; i++) {
    
    
        let view = wx.createSelectorQuery().select("#main-" + list[i].id);//执行到这里,发现下面的view.fields的callback 返回的永远是null
        view.fields({
    
    
          size: true
        }, data => {
    
    
          list[i].top = tabHeight;
          tabHeight = tabHeight + data.height;
          list[i].bottom = tabHeight;     
        }).exec();
      }
      that.setData({
    
    
        load: false,
        list: list
      })
      console.log(list)
    }
    let scrollTop = e.detail.scrollTop + 20;
    for (let i = 0; i < list.length; i++) {
    
    
      if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
    
    
        that.setData({
    
    
          VerticalNavTop: (list[i].id - 1) * 50,
          TabCur: list[i].id
        })
        return false
      }
    }
  }

问题:执行到这里,发现下面的view.fieldscallback 返回的永远是null
后来发现我的是一个Component,不能直接这么用

----------------------修改前-------------------------------


let view = wx.createSelectorQuery().select("#main-" + list[i].id); 
      view.fields({
    
    
        size: true
      }, data => {
    
    
        list[i].top = tabHeight;
        tabHeight = tabHeight + data.height;
        list[i].bottom = tabHeight;     
      }).exec();
    }


----------------------修改后-------------------------------

 let  view  = wx.createSelectorQuery().in(this).select("#main-" + list[i].id);

其他不变

在这里插入图片描述
示例

Component({
    
    
  queryMultipleNodes (){
    
    
    const query = wx.createSelectorQuery().in(this)
    query.select('#the-id').boundingClientRect(function(res){
    
    
      res.top // 这个组件内 #the-id 节点的上边界坐标
    }).exec()
  }
})

参考链接:https://www.cnblogs.com/taohuaya/p/11043518.html

猜你喜欢

转载自blog.csdn.net/iChangebaobao/article/details/107257375