1. In the process of uniapp project development, it is often necessary to obtain the height information of elements to more easily control the layout of elements. Usage scenarios: include dynamic calculation of the height of the container, set the minimum height of the component, etc.
In obtaining element node information, there are usually two situations: ① Obtaining a single ② Obtaining node information of v-for loop elements. Without further ado, let’s go directly to the code.
Note: Need to be obtained after onReady(), otherwise it will be invalid
①. Use uni.createSelectorQuery() to obtain node information
<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>
②. Use selectAll() to obtain the node information of the loop element.
<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>
2. At the same time, during development, we often encounter the need to calculate the remaining height of the page, which is used to set the height of other elements.
Implementation principle: First obtain the device height (uni.getSystemInfo()) minus the height of other containers, then it is the remaining height of the page
<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>