🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 一、概述 enquire.js 是轻量级,纯 JavaScript 实现的 CSS 媒体查询库; ## 二、安装 ``` npm install enquire.js ``` ## 三、API ``` enquire.register(mediaQuery, handler) mediaQuery: 字符串,需要响应的媒体。 handler: 函数或对象, ``` ``` enquire.unregister(mediaQuery[, handler]) mediaQuery: 字符串,需要注销响应的媒体。 handler: 函数或对象,可不写,一旦写了,只有这个handler被注销 ``` ## 四、应用 用register来注册响应处理方法,当检测到当前屏幕的尺寸信息后,触发处理器; ``` enquire.register("screen and (max-width:45em)", { // OPTIONAL // If supplied, triggered when a media query matches. match : function() {}, // OPTIONAL // If supplied, triggered when the media query transitions // *from a matched state to an unmatched state*. unmatch : function() {}, // OPTIONAL // If supplied, triggered once, when the handler is registered. setup : function() {}, // OPTIONAL, defaults to false // If set to true, defers execution of the setup function // until the first time the media query is matched deferSetup : true, // OPTIONAL // If supplied, triggered when handler is unregistered. // Place cleanup code here destroy : function() {} }); ``` ## 五、实例 1、创建device.js ``` /** * @description:监控屏幕宽度 * @create: **/ import enquireJs from 'enquire.js' // 引入enquire.js export const DEVICE_TYPE = { DESKTOP: 'desktop', TABLET: 'tablet', MOBILE: 'mobile' } export const deviceEnquire = function (callback) { const matchDesktop = { match: () => { callback && callback(DEVICE_TYPE.DESKTOP) } } const matchLablet = { match: () => { callback && callback(DEVICE_TYPE.TABLET) } } const matchMobile = { match: () => { callback && callback(DEVICE_TYPE.MOBILE) } } /** * enquireJs.register(mediaQuery, handler). * mediaQuery: 字符串,需要响应的媒体。 * handler: 函数或对象。 * handler Object: * match: 函数。媒体匹配时的回调。 */ enquireJs .register('screen and (max-width: 576px)', matchMobile) // mobile: 宽度小于576px时判断为mobile .register('screen and (min-width: 577px) and (max-width: 1299px)', matchLablet) // 宽度介于577px - 1299px 时判断为平板电脑 .register('screen and (min-width: 1300px)', matchDesktop) // 宽度大于1300px时判断为pc电脑 } ``` 2、在App.vue中加入 ``` mounted () { deviceEnquire(deviceType => { console.log('deviceType', deviceType) }) } ``` 3、可以将媒体的类型保存起来,就用到了Vuex;