为了响应使用多个CSS媒体查询
window.matchMedia()
,我们基本上只是多次重复上述一个媒体查询的蓝图。
为了简化代码,我们可以先使用数组存储所有
window.matchMedia()
查询,然后使用
for
循环来调用处理所有查询的单个函数。
让我们看看现在:
var mqls = [// window.matchMedia()查询列表
window.matchMedia(“(max-width:860px)”),
window.matchMedia(“(max-width:600px)”),
window.matchMedia(“(max-height:500px)”)]function mediaqueryresponse(mql){
document.getElementById(“match1”)。innerHTML = mqls [0] .matches // width:860px媒体匹配?
document.getElementById(“match2”)。innerHTML = mqls [1] .matches // width:600px媒体匹配?
document.getElementById(“match3”)。innerHTML = mqls [2] .matches // height:500px媒体匹配?}for(var i = 0; i <mqls.length; i ++){//循环查询
mediaqueryresponse(mqls [i])//在运行时显式调用处理函数
mqls [i] .addListener(mediaqueryresponse)//每当触发媒体查询时调用处理函数}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69933200/viewspace-2653082/ ,如需转载,请注明出处,否则将追究法律责任。