

English
MediaQueryObserver object, which is used to listen to the change of the status of the page media query, such as whether the width and height of the interface are within a specified range.
Create and return a MediaQueryObserver
object instance.
this description:
Custom component instance. The applet does not support this parameter, the input is only to smooth out the writing difference
Platform Compatibility
App | HarmonyOS Next | 微信小程序 | H5 | 支付宝小程序 | qq小程序 | 百度小程序 | 抖音小程序 | 飞书小程序 | 360小程序 | 快应用 | 元服务 | 小红书小程序 |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2.8.12+,app-vue | HBuilderX 4.31 | 基础库 2.11.1+ | √ | √ | √ | √ | √ | x | √ | x | x | x |
注意:支付宝小程序、qq小程序、百度小程序、抖音小程序,暂不支持监听屏幕动态改变,即只执行一次媒体查询。
tips: UI-related api will be executed after the component is mounted
方法 | 说明 |
---|---|
MediaQueryObserver.observe(Object descriptor, function callback) | Start listening to the changes of the page media query |
MediaQueryObserver.disconnect() | Stop listening to, and the callback function will no longer be triggered |
Object descriptor
Attribute name | Type | Defaults | Required | Instruction |
---|---|---|---|---|
minWidth | number | No | Page Minimum Width (in px) | |
maxWidth | number | No | Maximum page width (in px) | |
width | number | No | Page width (in px) | |
minHeight | number | No | Minimum page height (in px) | |
maxHeight | number | No | Maximum page height (in px) | |
height | number | No | Page height (in px) | |
orientation | string | No | Screen direction (landscape or portrait) |
The observe callback function contains one parameter
Parameter | Type | Instruction |
---|---|---|
matches | boolean | Whether the current status of the page meets the specified media query |
For the following sample code, it is recommended to use HBuilderX to create a new uni-app project, able to directly experience the complete example.
<template>
<view class="content">
<view class="">
要求页面最小宽度 375px, 且页面宽度最大 500px,是否匹配: {{matches}}
</view>
<view>
要求屏幕方向为纵向,是否匹配: {{landscape}}
</view>
</view>
</template>
<script>
let landscapeOb
export default {
data() {
return {
matches: false,
landscape: false,
mediaQueryOb: null
}
},
onLoad() {
},
//UI-related api will be executed after the component is mounted
mounted() {
this.testMediaQueryObserver()
this.landscapeObserver()
},
methods: {
testMediaQueryObserver() {
this.mediaQueryOb = uni.createMediaQueryObserver(this)
this.mediaQueryOb.observe({
minWidth: 375, //页面最小宽度 375px
}, matches => {
this.matches = matches;
})
},
landscapeObserver() {
landscapeOb = uni.createMediaQueryObserver(this)
landscapeOb.observe({
}, matches => {
this.landscape = matches
})
},
destroyed () {
landscapeOb.disconnect()
}
}
}
</script>
<style>
.content {
text-align: center;
height: 400upx;
}
</style>