在onload或在onready获取uniapp 获取元素高度一直返回null
时间: 2023-11-30 15:03:16 浏览: 242
在 `onload` 或者 `onready` 中获取元素高度返回 `null`,可能是因为元素还没有完全渲染完成,所以需要等到页面渲染完成后再获取元素高度。可以在 `mounted` 生命周期中使用 `this.$nextTick()` 来确保页面渲染完成后再获取元素高度,示例代码如下:
```
mounted() {
this.$nextTick(() => {
const height = this.$refs.element.offsetHeight; // 获取元素高度
});
},
```
其中,`this.$refs.element` 是需要获取高度的元素的引用,需要在元素上添加 `ref="element"` 属性。
相关问题
在onload或在onready获取uniapp 获取元素高度uni.createSelectorQuery().in(this).select('#newsRows').boundingClientRect((rect) => {一直返回null
可能是因为您的元素还没有完全加载完毕,导致在 `onload` 或 `onReady` 时获取高度时返回 null。您可以尝试在组件的 `mounted` 生命周期函数中获取元素的高度,因为在这个生命周期函数中,组件内的所有元素已经加载完毕。具体实现方法如下:
```js
mounted() {
uni.createSelectorQuery().in(this).select('#newsRows').boundingClientRect((rect) => {
console.log('元素的高度:', rect.height)
}).exec()
}
```
另外需要注意的是,在使用 `uni.createSelectorQuery()` 方法时,需要在方法后面添加 `.exec()` 才会真正执行查询操作。
uniapp获取元素高度
可以使用uni.createSelectorQuery()方法来获取元素的高度,具体步骤如下:
1. 在页面的onLoad或onReady生命周期函数中获取元素节点:
```
onLoad() {
uni.createSelectorQuery().select('.element').boundingClientRect(data => {
console.log(data.height) // 打印元素高度
}).exec()
}
```
2. 在页面中对应的元素上添加class名为“element”:
```
<view class="element">这是一个元素</view>
```
这样就可以获取到该元素的高度了。需要注意的是,使用uni.createSelectorQuery()方法获取元素高度时,必须等到元素渲染完成后才能获取到正确的高度,因此建议在onReady生命周期函数中获取元素高度。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)