js媒体查询

const mq = window.matchMedia('(max-width:400px)')
mq.addListener(mediaEvt)

funtion mediaEvt(mediaQuery) { //当屏幕=400时会执行这里的函数
  console.log(mediaQuery.match) // 当屏幕≤400时mediaQuery.match为true,否则为false
}

enquire.js是对上面该api的封装,使用方式如下

npm i enquire.js
import enquire from 'enquire'

enquire.register("screen and (max-width:1000px)", {

    match : function() {},      // OPTIONAL
                                // If supplied, triggered when the media query transitions
                                // *from an unmatched to a matched state*

    unmatch : function() {},    // OPTIONAL
                                // If supplied, triggered when the media query transitions
                                // *from a matched state to an unmatched state*.
                                // Also may be called when handler is unregistered (if destroy is not available)

    setup : function() {},      // OPTIONAL
                                // If supplied, triggered once immediately upon registration of the handler

    destroy : function() {},    // OPTIONAL
                                // If supplied, triggered when handler is unregistered. Place cleanup code here

    deferSetup : true           // OPTIONAL, defaults to false
                                // If set to true, defers execution the setup function
                                // until the media query is first matched. still triggered just once
});

posted on 2022-10-12 10:18  In-6026  阅读(39)  评论(0编辑  收藏  举报

导航