如何在JavaScript中使用媒体查询?
要将媒体查询与JavaScript结合使用,代码如下-
示例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; color: white; padding: 20px; } </style> </head> <body> <h1>Using media queries with JavaScript Example</h1> <h2>Resize the screen to see the color change from blue to red</h2> <script> var mediaQuery = window.matchMedia("(max-width: 700px)"); function setColor(mediaQuery) { if (mediaQuery.matches) { document.body.style.backgroundColor = "red"; } else { document.body.style.backgroundColor = "blue"; } } setColor(mediaQuery); mediaQuery.addListener(myFunction); </script> </body> </html>
输出结果
上面的代码将在窗口大小大于700px时产生以下输出-
调整浏览器窗口大小小于700px时-