> 技术文档 > uniapp APP、H5、小程序高度自适应布局解决方法_uniapp自适应布局

uniapp APP、H5、小程序高度自适应布局解决方法_uniapp自适应布局


很多人应该经常遇到,H5上面调试好的布局,到小程序或者APP上,各种手机分辨率切换后,高度就不一致了;

这里我分享一个我自己想到的解决办法;

比如,首页数据只允许一屏显示完,如图:

uniapp APP、H5、小程序高度自适应布局解决方法_uniapp自适应布局

想要实现这样的,屏幕不让滚动,兼容各种手机分辨率,高度始终都自适应的;

uniapp APP、H5、小程序高度自适应布局解决方法_uniapp自适应布局

代码示例:

<template><view class=\"bodys flex-column-nocenter\" :style=\"{\'height\':bodysHeight+\'px\'}\">//这里是整个页面的盒子<uv-navbar :placeholder=\"true\" bg-color=\"#fff\" title=\"首页\"></uv-navbar>//这是导航栏<view class=\"p-10 boxSizing h-100 flex1 flex-column-nocenter\">//这是除开导航栏外的盒子<view class=\"top\">//这是内部顶部的区域</view><view class=\"bbottom \" :style=\"{\'height\':bottomHeight+\'px\'}\">//内部底部区域<view class=\"cardBox2 mt-20 flex-column-nocenter\" :style=\"{\'height\':(bottomHeight/2)+\'px\'}\">//底部内需要自适应的父级盒子<view class=\"lengH\"></view><view class=\"charts-box\" :style=\"{\'height\':chartHeight+\'px\'}\">//底部内需要自适应的区域</view></view><view class=\"cardBox2 mt-20 flex-column-nocenter\" :style=\"{\'height\':(bottomHeight/2)+\'px\'}\">//底部内需要自适应的父级盒子<view class=\"lengH\"></view><view class=\"charts-box\" :style=\"{\'height\':chartHeight+\'px\'}\">//底部内需要自适应的区域</view></view></view></view></view></template><script>export default {data() {return {chartHeight:0,//charts-box高度bottomSafeArea:0,//兼容苹果手机底部安全区域高度topHeight:0,//状态栏导航栏高度screenHeight:0,//屏幕高度bodysHeight:0,//页面高度bottomHeight:0//底部容器高度}},onReady() {this.getServerData();},watch: {},mounted() {const systemInfo = uni.getSystemInfoSync();//获取系统设备信息this.screenHeight = systemInfo.screenHeight;//屏幕高度this.topHeight = uni.getSystemInfoSync().statusBarHeight;//顶部状态栏导航栏区域this.bottomSafeArea = getIphoneBottomHeight();//底部安全区域this.calculateNoticBoxHeight();//根据已知高度获取自适应的高度},methods: {//根据已知高度获取自适应的高度calculateNoticBoxHeight() {const query = uni.createSelectorQuery().in(this);query.select(\'.top\').boundingClientRect(data => {//html中top元素是因为有数据,可以直接获取到他的高度console.log(\"data=======\",data.height);//data.height 是 top元素高度 if (data) { this.bodysHeight = this.screenHeight - 90; //反正就得减去90,为什么我也不知道 this.bottomHeight = this.bodysHeight - data.height - this.topHeight - this.bottomSafeArea +20; //加20是因为有可能有margin或者padding,根据实际情况调整 }else{ console.log(\"22222222222\"); }}).exec();query.select(\'.lengH\').boundingClientRect(data => {console.log(\"data=======\",data.height); if (data) { this.chartHeight = (this.bottomHeight/2) - data.height - 30; //减去30是因为有可能有margin或者padding,根据实际情况调整 console.log(\"chartHeight\",this.chartHeight); this.$forceUpdate() }else{ console.log(\"22222222222\"); }}).exec();}},}</script><style scoped lang=\"scss\">.bodys {background-color: #eaeaea;padding-bottom: 20rpx;overflow: hidden;height: 100vh;}.top {width: 100%;height: 200rpx;background-color: $bg-index;border-radius: 10rpx;z-index: 9; }.charts-box { width: 100%; margin-top: 30rpx; }</style>