微信小程序在组件中获取界面上的节点信息wx.createSelectorQuery

时间:2019-06-18
本文章向大家介绍微信小程序在组件中获取界面上的节点信息wx.createSelectorQuery,主要包括微信小程序在组件中获取界面上的节点信息wx.createSelectorQuery使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

节点信息查询 API 可以用于获取节点属性、样式、在界面上的位置等信息。

最常见的用法是使用这个接口来查询某个节点的当前位置,以及界面的滚动位置。

示例代码:

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

上述示例中, #the-id 是一个节点选择器,与 CSS 的选择器相近但略有区别,请参见 SelectorQuery.select 的相关说明。

在自定义组件或包含自定义组件的页面中,推荐使用 this.createSelectorQuery 来代替 wx.createSelectorQuery ,这样可以确保在正确的范围内选择节点

将选择器的选取范围更改为自定义组件 component 内。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。

注:在小程序组件的ready生命周期中进行调用,即可获取节点信息。 

Component({
  methods: {

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

    
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行

    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
    ready: function(){
      console.log('ready');
      this.queryMultipleNodes ();// 获取节点信息

    }
  },
  

})

参考:

获取节点信息:

https://developers.weixin.qq.com/miniprogram/dev/framework/view/selector.html

组件中获取节点信息:

https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.in.html

组件生命周期:

https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html

原文地址:https://www.cnblogs.com/taohuaya/p/11043518.html