1、在pages.json中添加配置:
"globalStyle": {
"pageOrientation": "auto"
}
2、打开uniapp的manifest.json 文件,找到左侧菜单最后一栏 “源码视图”,点进去,在最底部添加以下代码
"orientation" : [
//竖屏正方向
"portrait-primary",
//竖屏反方向
"portrait-secondary",
//横屏正方向
"landscape-primary",
//横屏反方向
"landscape-secondary",
//自然方向
"default"
]
3、横竖屏自动切换的页面
说明:这个方案是指定某个页面 可根据用户手机横/竖自动切换,不过需要写两套样式,横竖各一套, 在data定义一个判断横竖的值,再搭配uniapp 页面生命周期onResize监听窗口的变化,横时isLandScape初始值为true,竖为false,给最外层view根标签的类样式使用三元判断动态绑定,isLandScape的值为true用横屏类样式,false用竖屏类样式。
1、我们先来看张效果图

2、需要横竖屏自动切换的页面写入
// 页面加载完给自然方向,它就能根据用户横竖自动切换
onLoad() {
// #ifdef APP-PLUS
plus.screen.lockOrientation('default');
// #endif
},
// 页面关闭时清除横屏正方向
onUnload() {
// #ifdef APP-PLUS
plus.screen.lockOrientation('portrait-primary');
// #endif
},
3、其他不需要横屏的页面 例如:index.vue
在两个生命周期中设置竖屏 并且关闭页面时清除
onLoad() {
// #ifdef APP-PLUS
plus.screen.lockOrientation('portrait-primary');
// #endif
},
onUnload() {
// #ifdef APP-PLUS
plus.screen.lockOrientation('portrait-primary');
// #endif
},
特别说明:// #ifdef APP-PLUS 与 // #endif 是让代码在app生效,解决plus is not defined的报错
4、核心逻辑代码
①、在data中初始一个判断横竖屏切换的值
isLandScape: false // 是否横屏,默认为竖屏
②、在页面生命周期onResize中监听窗口的变化
onResize() {
let _this = this
uni.getSystemInfo({
success: function(res) {
if (res.windowWidth > res.windowHeight) {
// 横屏
_this.isLandScape = true
} else {
// 竖屏
_this.isLandScape = false
}
}
})
}
5、在需要横竖屏切换的页面中用CSS预处理语言写两套样式(横/竖),我用的是scss
// 竖屏 chart_portrait是父类包裹层,tbcls只是我的表格样式,你可以根据你的具体需求写相应的样式
.chart_portrait {
height: 36vh;
font-size: 2vh;
text-align: center;
.tbcls {
width: 97vw;
}
}
// 横屏
.chart_lanscape {
height: 82vh;
font-size: 2vw;
text-align: center;
.tbcls {
width: 98vw;
}
}
6、用三元判断data中的isLandScape是否为false,是的话为竖屏,那么就用竖屏类样式,否则用横屏类样式
<view :class="{'chart_portrait': !isLandScape, 'chart_lanscape': isLandScape}">
</view>
完整代码:
<template>
<view>
<view :class="{'chart_portrait': !isLandScape, 'chart_lanscape': isLandScape}">
</view>
</view>
</template>
<script>
export default {
data() {
return {
isLandScape: false
}
},
onResize() {
let _this = this
uni.getSystemInfo({
success: function(res) {
if (res.windowWidth > res.windowHeight) {
// 横屏
_this.isLandScape = true
} else {
// 竖屏
_this.isLandScape = false
}
}
})
},
methods:{
}
}
</script>
<style >
/* // 竖屏 chart_portrait是父类包裹层,tbcls只是我的表格样式,你可以根据你的具体需求写相应的样式 */
.chart_portrait {
height: 36vh;
font-size: 2vh;
text-align: center;
background-color: #ff0000;
}
/* // 横屏 */
.chart_lanscape {
height: 82vh;
font-size: 2vw;
text-align: center;
background-color: aqua;
}
</style>
该博客介绍了Uni-app页面横竖屏自动切换的方案。需在pages.json和manifest.json添加配置,指定页面根据手机横竖自动切换,要写横竖两套样式。在data定义判断值,搭配页面生命周期onResize监听窗口变化,用三元判断动态绑定类样式。还提及非横屏页面设置及核心逻辑代码。
5717

被折叠的 条评论
为什么被折叠?



