window.matchMedia(mediaQueryString)
mediaQueryString: 必需,一个字符串,表示即将返回一个新 MediaQueryList 对象的媒体查询 min-height, min-width, orientation等。
function myFunction() { var x = document.getElementById("demo"); if (window.matchMedia("(max- 700px)").matches) { console.log(window.matchMedia("(max- 700px)")) x.innerHTML = "窗口小于或等于 700 像素"; } else { x.innerHTML = "窗口大于 700 像素"; } }
MediaQueryList 对象还可以监听事件。通过监听,在查询结果发生变化时,就调用指定的回调函数。
方法 | 描述 |
---|---|
addListener(functionref) | 添加一个新的监听器函数,该函数在媒体查询的结果发生变化时执行。 |
removeListener(functionref) | 从媒体查询列表中删除之前添加的监听器。 如果指定的监听器不在列表中,则不执行任何操作。 |