CSS

媒体查询:测试媒体查询 | Media Queries: Testing media queries

媒体查询:测试媒体查询

DOM提供了可以测试一个媒体查询编程的结果的功能,通过MediaQueryList接口和它的方法和属性。

创建媒体查询列表

在计算媒体查询的结果之前,需要创建MediaQueryList表示查询的。若要执行此操作,请使用window.matchMedia方法。

例如,若要设置一个查询列表,以确定设备是否处于横向或纵向方向,请执行以下操作:

var mediaQueryList = window.matchMedia("(orientation: portrait)"

检查查询结果

一旦您创建了媒体查询列表,就可以通过查看其值来检查查询结果。matches拥有值

if (mediaQueryList.matches) { /* The viewport is currently in portrait orientation */ } else { /* The viewport is not currently in portrait orientation, therefore landscape */ }

接收查询通知

如果您需要持续地了解对查询的计算结果的更改,则注册一个听者而不是轮询查询%27的结果。要做到这一点,请调用addListener()方法的MediaQueryList对象,并在媒体查询状态更改%28e时调用回调函数。,媒体查询测试将从truefalse29%:

var mediaQueryList = window.matchMedia("(orientation: portrait)" // Create the query list. function handleOrientationChange(mql) { ... } // Define a callback function for the event listener. mediaQueryList.addListener(handleOrientationChange // Add the callback function as a listener to the query list. handleOrientationChange( // Run the orientation change handler once.

此代码创建定向测试媒体查询列表,然后向其添加一个事件侦听器。添加监听器后,我们还直接调用侦听器。这使得侦听器根据当前设备方向执行调整;否则,我们的代码可能假设设备在启动时处于纵向模式,即使它实际上处于横向模式。

handleOrientationChange()函数将查看查询的结果,并处理任何我们需要做的方向更改:

function handleOrientationChange(evt) { if (evt.matches) { /* The viewport is currently in portrait orientation */ } else { /* The viewport is currently in landscape orientation */ } }

上面,我们将参数定义为evt- 一个事件对象。这是有道理的,因为以标准方式更新的MediaQueryList句柄事件监听器的实现。他们不再使用不同寻常的MediaQueryListListener机制,而是使用标准的事件监听器设置,将类型为事件的事件对象MediaQueryListEvent作为参数传递给回调函数。

此事件对象还包括mediamatch属性的这些特性,因此可以查询MediaQueryList直接访问它,或者访问事件对象。

结束查询通知

若要停止接收有关媒体查询值更改的通知,请调用removeListener()MediaQueryList,将先前定义的回调函数的名称传递给它:

mediaQueryList.removeListener(handleOrientationChange

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9(Yes)6.0 (6.0)1012.15
New version spec update(Yes)?55 (55)No support(Yes)?

FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support?(Yes)?????
New version spec updateNo support?55.0 (55)No support(Yes)?(Yes)