wxml页面

给需要获取高度的view标签添加一个id

<view class=\'jbox\' id="test">test</view>

.JS文件

通常是这样写,写在onReady,页面初次渲染完成里面。

 onReady: function (e) {
      var query = wx.createSelectorQuery()
      query.select(\'#test\').boundingClientRect(function (res) {
         cosole.log(res);
      }).exec();
  },

如果数据是api获取的,wxml页面上使用了for循环,把获取高度写在页面渲染完成之后,这样可以避免获取到的高度不准确。

  onLoad: function (e) {
    var that = this;
    // 调用api接口
    wx.request({
      url: \'你的接口地址\', //接口地址
      header: {
        \'content-type\': contenttype, // 默认值
      },
      success: function (res) {
      console.log(\'接口返回参数\',res);
        that.setData({
          test: \'test\', // 需要传到页面的参数
        },()=>{
          var query = wx.createSelectorQuery()
          query.select(\'#test\').boundingClientRect(function (res) {
            cosole.log(res);
          }).exec();
        });
      },
    })
  },

api获取数据,写在不同地方得到的不同结果。
在这里插入图片描述

相关文章: