MediaQueryList.addListener()

MediaQueryList接口的addListener()方法向MediaQueryListener添加一个侦听器,该侦听器将运行自定义回调函数以响应媒体查询状态的更改。

从本质上讲,这是EventTarget.addEventListener()的别名,用于向后兼容。 较旧的浏览器应使用addListener而不是addEventListener,因为MediaQueryList仅从较新的浏览器中的EventTarget继承。

语法

MediaQueryList.addListener(func)

参数

func
表示您要在媒体查询状态更改时运行的回调函数的函数或函数引用。 在原始实现中,回调是一个非标准的MediaQueryListListener对象。 在新的实现中,使用标准事件机制,回调是标准函数,事件对象是MediaQueryListEvent,它继承自Event

返回值

Void.

例子

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

function screenTest(e) {
  if (e.matches) {
    /* the viewport is 600 pixels wide or less */
    para.textContent = 'This is a narrow screen — less than 600px wide.';
    document.body.style.backgroundColor = 'red';
  } else {
    /* the viewport is more than than 600 pixels wide */
    para.textContent = 'This is a wide screen — more than 600px wide.';
    document.body.style.backgroundColor = 'blue';
  }
}

mql.addListener(screenTest);

规范

Specification Status Comment
CSS Object Model (CSSOM) View Module
addListener
Working Draft Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
addListenerChrome Full support 9Edge Full support 12Firefox Full support 6IE Full support 10Opera Full support 12.1Safari Full support 5.1WebView Android Full support YesChrome Android Full support 18Firefox Android Full support YesOpera Android Full support YesSafari iOS Full support 5Samsung Internet Android Full support 1.0

Legend

Full support  
Full support

参见