刚开始想用媒体查询,但是解析媒体查询识别不出来
@media only screen and (device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2){
}
@media only screen and (device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio:3){
}
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio:3){
}
如果用下面的方法,则控制不住,方法都会走:
@media only screen and (max-width: 375px) and (max-height: 667px) {
}
@media only screen and (max-width: 414px) and (max-heigh: 736px){
}
@media only screen and (max-width: 375px) and (max-heigh: 812px){
}
这种没试出来
然后发现一种新的方案:
<template>
<view class="content" :class="{'hengBox': matches, 'shuBox':landscape }">
<view class="">
要求页面最小宽度 375px, 且页面宽度最大 500px,是否匹配: {
{
matches}}
</view>
<view>
要求屏幕方向为纵向,是否匹配: {
{
landscape}}
</view>
<button type="default" @click="goHome()">点击home</button>
</view>
</template>
<script>
let landscapeOb
export default {
data() {
return {
matches: false,
landscape: false,
mediaQueryOb: null
}
},
onLoad() {
},
// 和 UI 相关的 api 在组件 mountd 后执行
mounted() {
this.testMediaQueryObserver()
this.landscapeObserver()
},
methods: {
goHome(){
uni.switchTab({
url: '../home/index'
})
},
testMediaQueryObserver() {
this.mediaQueryOb = uni.createMediaQueryObserver(this)
this.mediaQueryOb.observe({
minWidth: 375, //页面最小宽度 375px
maxWidth: 960 //页面宽度最大 500px
}, matches => {
this.matches = matches;
})
},
landscapeObserver() {
landscapeOb = uni.createMediaQueryObserver(this)
landscapeOb.observe({
orientation: 'landscape' //屏幕方向为纵向
}, matches => {
this.landscape = matches
})
},
destroyed () {
this.mediaQueryOb.disconnect() //组件销毁时停止监听
landscapeOb.disconnect()
}
}
}
</script>
<style>
.content {
text-align: center;
height: 400upx;
}
.hengBox{
background-color: #DD524D;
}
.shuBox{
width: 960px;
margin: 0 auto;
background-color: #007AFF;
}
</style>
上面这种方案就是判断横屏竖屏的两个变量 根据变量动态绑定最外层的样式,屏幕超出时居中展示