Is the screen/viewport greater than 700 pixels wide:
if (window.matchMedia("(max-width: 700px)").matches) {
// Viewport is less or equal to 700 pixels wide
} else {
// Viewport is greater than 700 pixels wide
}
Try it Yourself »
The matchMedia()
method returns a MediaQueryList with the results from the query.
The media queries of the matchMedia()
method can be any of the media features of the CSS @media rule, like min-height, min-width, orientation, etc.
matchMedia("(max-height: 480px)").matches);
matchMedia("(max-width: 640px)").matches);
window.matchMedia(
mediaQuery)
Parameter | Description |
mediaQuery | Required. A string representing a media query. |
Type | Description |
An object | A MediaQueryList object with the results of the media query. |
The first example on this page runs a media query and compares it to the current window state.
To run responsive media query whenever the window state changes, add an event listener to the MediaQueryList object (See "More Examples" below):
If the viewport is less or equal to 500 pixels wide, set background color to yellow, otherwise to pink:
// Create a match Function
function myFunction(x) {
if (x.matches) {
document.body.style.backgroundColor = "yellow";
} else {
document.body.style.backgroundColor = "pink";
}
}
// Create a MediaQueryList object
const mmObj = window.matchMedia("(max-width: 500px)")
// Call the match function at run time
myFunction(mmObj);
// Add the match function as a listener for state changes
mmObj.addEventListener("change", function() {
myFunction(mmObj);
});
Try it Yourself »
matchMedia()
is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!