小程序获取当前元素在屏幕中的位置

7,888 阅读1分钟

wxml:

<view class="usermotto" style="height:213px;" id='the-id'/>

js:

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

注意:

  1. 坐标以元素左上角为顶点计算
  2. 在在自定义组件或包含自定义组件的页面中,应使用 this.createSelectorQuery() 来代替wx.createSelectorQuery()。

参考 :https://developers.weixin.qq.com/miniprogram/dev/api/wx.createSelectorQuery.html