uniapp获取页面高度与元素高度简单示例
作者:资源驿站时间:2026-10-30 23:48:29浏览:305
本文介绍在uniapp中获取页面总高度与指定DOM元素高度的方法。通过uni.getSystemInfoSync()获取系统信息中的页面高度,利用uni.createSelectorQuery().in(this)结合boundingClientRect获取特定元素的高度。示例代码展示了如何在mounted生命周期中执行查询,并输出高度数值。
一、获取页面高度
利用uni.getSystemInfoSync()接口能够获取系统相关信息,其中包含了页面高度等关键数据。
const { windowHeight } = uni.getSystemInfoSync(); // 获取页面高度二、获取元素高度
假设存在一个金刚区,我们需要获取该区域的高度:
<view class="square_giant">
<block v-for="item in giantList" :key="item.id">
<view class="square_giant_item">
<image :src="item.image || ''" mode=""></image>
<text>{{ item.title || '' }}</text>
</view>
</block>
</view>const query = uni.createSelectorQuery().in(this);
query.select('.square_giant').boundingClientRect(({ height }) => {
console.log('square_giant的高度是:' + height + 'px');
}).exec();附:uniapp获取元素的宽度、高度
完整代码
重要:mounted( ){ }代表页面已被渲染
<template>
<view>
<view class="xxoo" style="height: 650rpx; border: 3rpx orange solid; margin: 30rpx; background-color: #C0C0C0; padding: 30rpx;">
<view>
元素class="xxoo"
</view>
<view>
获取当前元素的实时高度为:{{heightEle}}
</view>
<view>
推荐无广告的百度首页 https://baidu.rudon.cn
</view>
<view>
推荐无广告的手机浏览器 https://viayoo.com/zh-cn/
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
heightEle: 0
}
},
methods: {
},
mounted() {
uni.createSelectorQuery().in(this).select(".xxoo").boundingClientRect(data => {
console.log(JSON.stringify(data))
// {"id":"","dataset":{},"left":12,"right":308,"top":12,"bottom":315,"width":296,"height":303}
this.heightEle = data.height
}).exec()
},
onLoad () {
}
}
</script>
<style>
</style>总结
到此这篇关于uniapp获取页面高度与元素高度的文章就介绍到这了,更多相关uniapp获取页面与元素高度内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
作者最新文章
JS中使用位运算(~~)和一元加号(+)快速转换字符串为整数
2026-11-03 22:41:12
怎么使用命令行批量格式化项目中的JS文件
2026-11-03 19:04:42
JS代码美化后报错怎么办?常见格式化冲突解决方法
2026-11-03 18:47:01
不用moment.js,怎么用原生JS Intl API格式化时间戳
2026-11-03 18:10:30
原生JS与dayjs获取当前日期的代码对比
2026-11-03 17:57:26
