目录

小程序获取元素信息

目录

小程序获取元素信息

https://img-home.csdnimg.cn/images/20240715101418.png

关键词由CSDN通过智能技术生成

遇到问题 :wx.createSelectorQuery() 返回值为null

   <view style="width: 200px;height: 200px;border: 1px solid red;" id="content">
     dom元素
   </view>
  let query = wx.createSelectorQuery();
  query.select("#content").boundingClientRect();
  query.exec(function (res) {
      console.log(res);// null

  });

原因 :此属性只会选取页面范围内的节点

  • 如果将选择器的选取范围更改为自定义组件 component 内。
  • (初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)
  • 所以就造成页面渲染时,获取不到当前节点

官网链接:

解决方法 :将wx.createSelectorQuery()改为wx.createSelectorQuery().in(this)

   <view style="width: 200px;height: 200px;border: 1px solid red;" id="content">
     dom元素
   </view>
  let query = wx.createSelectorQuery().in(this);
  query.select("#content").boundingClientRect();
  query.exec(function (res) {
      console.log(res);// null
     // .top 节点的上边界坐标
     // .scrollTop显示区域的竖直滚动位置

  });

注意

  1. 如果获取的元素,节点上有wx:if或者节点的元素上有wx:for,那么如果是在数据渲染之前获取的话,那么也是获取不到元素的,只有渲染之后,才能获取到元素,可以加定时器解决
  2. 如果元素添加了margin值的话,也是获取不到的