在onload或在onready获取uniapp 获取元素高度uni.createSelectorQuery().in(this).select('#newsRows').boundingClientRect((rect) => {一直返回null
时间: 2024-02-03 12:14:03 浏览: 36
可能是因为您的元素还没有完全加载完毕,导致在 `onload` 或 `onReady` 时获取高度时返回 null。您可以尝试在组件的 `mounted` 生命周期函数中获取元素的高度,因为在这个生命周期函数中,组件内的所有元素已经加载完毕。具体实现方法如下:
```js
mounted() {
uni.createSelectorQuery().in(this).select('#newsRows').boundingClientRect((rect) => {
console.log('元素的高度:', rect.height)
}).exec()
}
```
另外需要注意的是,在使用 `uni.createSelectorQuery()` 方法时,需要在方法后面添加 `.exec()` 才会真正执行查询操作。
相关问题
在onload或在onready获取uniapp 获取元素高度一直返回null
在 `onload` 或者 `onready` 中获取元素高度返回 `null`,可能是因为元素还没有完全渲染完成,所以需要等到页面渲染完成后再获取元素高度。可以在 `mounted` 生命周期中使用 `this.$nextTick()` 来确保页面渲染完成后再获取元素高度,示例代码如下:
```
mounted() {
this.$nextTick(() => {
const height = this.$refs.element.offsetHeight; // 获取元素高度
});
},
```
其中,`this.$refs.element` 是需要获取高度的元素的引用,需要在元素上添加 `ref="element"` 属性。
uni.createSelectorQuery()使用方法
uni.createSelectorQuery()是用来获取页面上的节点信息的API,可以用来获取节点的位置、尺寸、样式等信息。具体使用方法如下:
1. 在页面的onLoad生命周期函数中,创建一个selectorQuery对象:
```
let query = uni.createSelectorQuery()
```
2. 使用selectorQuery对象的方法来选择需要获取信息的节点,例如:
```
query.select('#my-node').boundingClientRect()
```
其中,#my-node是需要获取信息的节点的id,boundingClientRect()是获取节点的位置、尺寸等信息的方法。
3. 使用exec()方法来执行获取信息的操作,并在回调函数中处理获取到的信息:
```
query.exec(function(res) {
console.log(res[0].width) // 获取节点的宽度
})
```
其中,res是一个数组,每个元素对应一个之前选择的节点,数组中的每个元素都包含了该节点的位置、尺寸、样式等信息。
完整示例代码如下:
```
export default {
onLoad() {
let query = uni.createSelectorQuery()
query.select('#my-node').boundingClientRect()
query.exec(function(res) {
console.log(res[0].width) // 获取节点的宽度
})
}
}
```