English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
matchMedia()The method returns a new MediaQueryList object representing the parsed result of the specified media query string.
The value of the matchMedia() method can beCSS @media ruleAny media feature, such as min-height, min-width, orientation, etc.
window.matchMedia(mediaQueryString)
if (window.matchMedia("(min-width: 500px)").matches) { /* Viewport minimum is500 pixels wide */ } /* Viewport width less than500 pixels */ }Test and See‹/›
The numbers in the table specify the first browser version that fully supports the matchMedia() method:
Method | |||||
matchMedia() | 9 | 6 | 12.1 | 5.1 | 10 |
Parameter | Description |
---|---|
mediaQueryString | A string representing the media query for which a new MediaQueryList object is to be returned |
Return Value: | A MediaQueryList object representing the result of the specified CSS media query string |
---|
If the viewport width is less than or equal to600 pixels, the background color will be coral. If greater than600, it will turn light green:
var size = window.matchMedia("(max-width: 600px)") myFunc(size) // Call listener function at runtime size.addListener(myFunc) // Attach listener function when the state changes function myFunc(size) { if (size.matches) { document.body.style.backgroundColor = "coral"; } document.body.style.backgroundColor = "lightgreen"; } }Test and See‹/›
CSS Tutorial:CSS Media Queries