Core points
window.matchMedia
API in JavaScript allows detection of CSS3 media query status changes. It returns a MediaQueryList
object that can be used to determine if a specific media query matches the current device and can add an event listener in response to changes. This article was written in 2011 and updated in 2018. When responsive design was first introduced, it was one of the most exciting concepts of web layout since CSS took the representation grid. The underlying technology uses media queries to determine the type, width, height, orientation, resolution, aspect ratio, and color depth of viewing devices to provide different style sheets. If you think responsive design is limited to CSS layouts, you'll be happy to hear that media queries can also be used in JavaScript, which will be explained in this article.
Media Query in CSS
In the following example, cssbasic.css
is provided to all devices. However, if the horizontal width of the screen is 500 pixels or more, it will also be sent csswide.css
:
<link rel="stylesheet" media="all" href="cssbasic.css" /> <link rel="stylesheet" media="(min-width: 500px)" href="csswide.css" />
The possibilities are endless, and the technology has been used for a long time by most websites on the Internet. Adjusting the size of the browser width will trigger changes in the page layout. Today, using media queries makes it easy to resize designs or elements in CSS. But what if you need to change content or features? For example, on smaller screens, you might want to use shorter titles, fewer JavaScript libraries, or modify operations of widgets. The viewport size can be analyzed in JavaScript, but this is a bit confusing:
window.innerWidth
and window.innerHeight
. (The weird mode versions before IE 10 require document.body.clientWidth
and document.body.clientHeight
.) window.onresize
document.documentElement.clientWidth
and document.documentElement.clientHeight
, but it is inconsistent. Depending on the browser and mode, the size of the window or document will be returned. Even if you successfully detect changes in viewport size, you must calculate factors such as direction and aspect ratio yourself. There is no guarantee that it matches the browser's assumption when applying media query rules in CSS.
How to write media queries using JavaScript code
Luckily, it is possible to respond to changes in CSS3 media query status in JavaScript. The key API is window.matchMedia
. This will pass the same string as the media query string used in CSS media query:
<link rel="stylesheet" media="all" href="cssbasic.css" /> <link rel="stylesheet" media="(min-width: 500px)" href="csswide.css" />
matches
attribute returns true
or false
based on the query result. For example:
const mq = window.matchMedia("(min-width: 500px)");
You can also add an event listener that fires when a change is detected:
if (mq.matches) { // 窗口宽度至少为 500 像素 } else { // 窗口宽度小于 500 像素 }
You should also call the handler directly after defining the event. This will ensure that your code can be initialized itself during or after page loading. Without it, WidthChange()
will never be called if the user has not changed the browser size. At the time of writing, matchMedia
has excellent browser support in every way, so there is no reason not to use it in a production environment. Check out the following demonstration text to change dynamically from "More than 500 pixels" to "less than 500 pixels" depending on your browser window size. Or, download the sample code: CodePen demo link
Frequently Asked Questions about JavaScript Media Query (FAQ)
(The FAQ section should be preserved and improved here to make it more concise and clearer and use a clearer format.) I cannot rewrite the FAQ section in full due to space limitations, but here are some Improvement suggestions:
With the above improvements, the FAQ part can be made easier to read and understand.
The above is the detailed content of How to use Media Queries in JavaScript with matchMedia. For more information, please follow other related articles on the PHP Chinese website!