Window matchMedia()Method

Window 对象参考手册Window Object


Definition and Usage

matchMedia() returns a new MediaQueryList object representing the parsed result of the specified media query string.

The value of the matchMedia() method can be any one of theCSS @media rulesfeatures, such asmin-height, min-width, orientationetc.

The MediaQueryList object has the following two properties:

  • media: the content of the query statement.
  • matches: used to detect the query result. If the document matches the media query list, the value is true; otherwise, it is false.

MediaQueryListThe object can also listen for events. By listening, when the query result changes, the specified callback function is called.

Method Description
addListener(functionref) Adds a new listener function that executes when the result of the media query changes.
removeListener(functionref) Removes a previously added listener from the media query list. If the specified listener is not in the list, no operation is performed.

Syntax

window.matchMedia(mediaQueryString)

Parameter description:

  • mediaQueryString: Required. A string representing the media query for which a new MediaQueryList object will be returned.

Return Value

Returns a MediaQueryList object.

Browser Support

The numbers in the table indicate the first browser version that supports the method.

Method
matchMedia() 9.0 10.0 6.0 5.1 12.1

Examples

Examples

Determine the screen (screen/viewport) window size:

if (window.matchMedia("(max-width: 700px)").matches) { /*Window less than or equal to 700 pixels*/ } else { /*Window greater than 700 pixels*/ }

Try it Yourself »

Examples

Determine the screen (screen/viewport) window size. When it is less than or equal to 700 pixels, change the background color to yellow; when it is greater than 700 pixels, change the background color to pink:

function myFunction(x) { if (x.matches) { //Media query document.body.style.backgroundColor = "yellow"; } else { document.body.style.backgroundColor = "pink"; } } var x = window.matchMedia("(max-width: 700px)") myFunction(x) //The listener function called when executing x.addListener(myFunction) //Add a listener when the state changes

Try it Yourself »

Window 对象参考手册Window Object

Other Extensions