最近搜索

小程序 获取 元素的 高度 和 距离顶部的距离

浏览:10
管理员 2025-06-29 12:25




util.js代码  旅游小程序里面有

/**获取元素绝对位置(相对于页面顶部) 
  #type_list设置padding-top 100 或者 10  获得的值都一样
 var this_ = this;
  this.getAbsolutePosition('#type_list').then(pos => {
    console.log('type_list绝对位置:', pos.top, pos.left)
    this_.setData({
      type_list_top: pos.top
    })
  })
 * */
export function getAbsolutePosition(selector) {
  return new Promise((resolve) => {
    // 获取元素位置
    wx.createSelectorQuery()
      .select(selector)
      .boundingClientRect(rect => {
        // 获取页面滚动位置
        wx.createSelectorQuery()
          .selectViewport()
          .scrollOffset(scroll => {
            const absoluteTop = rect.top + scroll.scrollTop
            resolve({
              top: absoluteTop,
              left: rect.left + scroll.scrollLeft
            })
          }).exec()
      }).exec()
  })
}


/**
 * 获取指定元素的高度。
 
 这个高 是包含 padding 的
padding-top: 25rpx   height=  57
修改padding-top: 85rpx; height=  88
padding加了 60rpx   heght从57涨到了88   加了  31

 *var this_ = this;
    get_dom_height('#type_list').then(res => {
      console.log('高度:', res.height )
      this_.setData({
        height:  res.height
      })
    })
 */
export function get_dom_height(selector) {
  return new Promise((resolve) => {
    const query = wx.createSelectorQuery()
    query.select(selector).boundingClientRect(rect => {
      console.log(selector+'高度:', rect.height);
      resolve({
        height: rect.height
      })
    }).exec()
  })
}




页面使用代码

    /**
   * 获取分类列表的高度
   * 参数 #type_list
   */
  get_type_list_height() {
    get_dom_height("#type_list").then(res=>{
      this.setData({
        type_list_height: res.height
      })
    });
  },




获得的高度 和看到的一样。



image.png


image.png




联系站长

站长微信:xiaomao0055

站长QQ:14496453