window.matchMedia 办法

window.matchMedia 办法返回一个 MediaQueryList 对象。window.matchMedia 承受 媒体查问字符串 作为参数。

const mql1 = window.matchMedia('(max-width: 600px)');const mql2 = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

MediaQueryList 对象

属性 matches

返回一个 boolean 值。判断以后的 document 是否匹配 媒体查问字符串。匹配返回 true。否则返回 false。

const mql = window.matchMedia('(max-width: 600px)');mql.matches

不匹配 媒体查问字符串

匹配 媒体查问字符串

属性 media

返回 媒体查问字符串

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');// "(min-width: 400px) and (max-width: 800px)"mql.media

办法 addListener

为 MediaQueryList 对象增加一个监听器。

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');const callback = function () {    if (mql.matches) {        console.log('匹配')    } else {        console.log('不匹配')    }}mql.addListener(callback)

只有当 mql。matches 发生变化的时候, callback 才会调用。如果想要一开始就执行逻辑。能够手动的调用一遍 callback

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');const callback = function () {    if (mql.matches) {        console.log('匹配')    } else {        console.log('不匹配')    }}callback()mql.addListener(callback)

办法 removeListener

用于移除监听器

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');const callback = function () {    if (mql.matches) {        console.log('匹配')    } else {        console.log('不匹配')    }}mql.addListener(callback)mql.removeListener(callback)

参考

  • Window.matchMedia
  • MediaQueryList