uniapp怎么获取元素高度,获取元素节点信息,获取界面剩余高度
一、在uniapp项目开发的过程中,常常需要获取元素的高度信息,来更容易的实现元素的布局控制,使用场景:列入动态的计算容器的高度,设置组件的最小高度等等
在获取元素节点信息中,通常有两种情况:①获取单个 ②获取v-for循环元素的节点信息,话不多说,直接上代码
注意:需要在onReady()之后获取,否则无效
①、使用uni.createSelectorQuery()来获取节点信息
<template> <view> <view class="box"></view> </view> </template> <script> export default { data() { return { } }, onReady() { //.box获取class为box的元素,如果使用的id= 'box' 则使用'#box' uni.createSelectorQuery().select('.box').boundingClientRect(data => { console.log(data) }).exec() }, methods: { } } </script> <style> .box { height: 100px; width: 200px; background-color: pink; } </style>
②、通过selectAll()来实现获取循环元素的节点信息
<template> <view> <view class="box" v-for="item in 4"></view> </view> </template> <script> export default { data() { return { } }, onReady() { //.box获取class为box的元素,如果使用的id= 'box' 则使用'#box' uni.createSelectorQuery().selectAll('.box').boundingClientRect(data => { console.log(data) }).exec() }, methods: { } } </script> <style> .box { height: 100px; width: 200px; background-color: pink; } </style>
二、 同时在开发中常常还会遇到需要计算页面剩余高度,用于设置其他元素的高度
实现原理:首先获取设备高度(uni.getSystemInfo())减去其他容器的高度,则为页面剩余高度
<template> <view> <view class="box"></view> </view> </template> <script> export default { data() { return { } }, onReady() { uni.getSystemInfo({ success(res) { let screenHeight = res.screenHeight let height = '' //.box获取class为box的元素,如果使用的id= 'box' 则使用'#box' uni.createSelectorQuery().select('.box').boundingClientRect(data => { height = screenHeight - data.height console.log(height) }).exec() } }) }, methods: { } } </script> <style> .box { height: 100px; width: 200px; background-color: pink; } </style>
分类:
前端开发常用技巧
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现