一起创业网-为互联网创业者服务

小程序控件高度怎么获取

在微信小程序中,获取控件高度的方法主要有以下几种:

使用 `wx.createSelectorQuery`

在 `wxml` 中给控件一个 `id`。

在 `js` 中使用 `wx.createSelectorQuery` 选择对应 `id` 的节点,并通过 `boundingClientRect` 获取节点的高度。

示例代码:

```javascript

var query = wx.createSelectorQuery();

query.select('myText').boundingClientRect();

query.exec(function (res) {

console.log(res.height);

});

```

使用 `wx.getSystemInfoSync`

获取系统信息,包括窗口高度、状态栏高度等,然后通过计算得出控件的高度。

示例代码:

```javascript

let res = wx.getSystemInfoSync();

let statusHeight = res.statusBarHeight;

let navBarHeight = (custom.top - statusHeight) * 2 + custom.height;

```

在 `page.json` 中设置 `custom` 为 `true`,然后在 `tabBar` 组件上绑定一个 `id`,接着在页面的 `onLoad` 生命周期函数中使用 `wx.createSelectorQuery` 方法获取 `tabBar` 组件的高度。

示例代码:

```javascript

Page({

onLoad: function () {

const query = wx.createSelectorQuery();

query.select('myTabBar').boundingClientRect();

query.exec(function (res) {

console.log(res.height);

});

}

});

```

在 `onCreate` 方法中获取控件的高度

在 `onCreate` 方法中通过 `view.getHeight()` 获取控件的高度。

示例代码:

```javascript

onCreate: function () {

this.view.getHeight(function (height) {

console.log(height);

});

}

```

这些方法可以帮助你在微信小程序中获取控件的高度。根据具体需求选择合适的方法即可。