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>
posted @ 2024-03-21 14:23  小闫的姑娘  阅读(248)  评论(0编辑  收藏  举报