微信小程序自定义组件中获取页面元素到顶部的距离

793 阅读1分钟

描述:需要在页面滚动到指定位置设置元素的fixed属性,在自定义组件中的元素,按照官方给出的方法始终拿不到元素信息,后来查阅了资料才发现,需要设置in(this)才可以。

index.wxml

<view class="menudrop">页面中的元素</view>

index.js

Component({
    lifetimes: {
        // 在ready生命周期函数中
        ready() {
          let query = wx.createSelectorQuery().in(this)
          query.select('.menudrop').boundingClientRect((rect) => {
            console.log(rect)
            // let top = rect.top
          }).exec()
        }
      },
})