uniapp自动修改屏幕宽高
时间: 2023-06-19 10:03:35 浏览: 67
Uniapp 可以通过 `uni.getSystemInfo` 方法获取设备信息,包括屏幕宽高等信息。可以在 `onLoad` 或 `onReady` 生命周期内获取设备信息,然后根据设备的屏幕宽高动态修改页面元素的大小和布局。
例如,可以在 `onLoad` 生命周期内获取设备信息并设置 `rootFontSize`,然后在样式表中使用 `rem` 单位来布局页面,以实现自适应屏幕大小的效果:
```javascript
onLoad() {
uni.getSystemInfo({
success: res => {
// 设备屏幕宽度除以 375(设计稿宽度)并乘以 100,得到 rootFontSize
const rootFontSize = (res.windowWidth / 375) * 100
// 将 rootFontSize 设置为 html 的 font-size
uni.$emit('setRootFontSize', rootFontSize)
}
})
}
```
在 App.vue 中监听 `setRootFontSize` 事件,然后设置 html 的 font-size:
```html
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
mounted() {
uni.$on('setRootFontSize', rootFontSize => {
document.documentElement.style.fontSize = `${rootFontSize}px`
})
}
}
</script>
<style>
/* 使用 rem 布局 */
.example {
width: 3.2rem;
height: 1.6rem;
}
</style>
```
这样,无论设备屏幕大小如何,页面元素的大小和布局都会自动适应屏幕大小。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)