如何使用 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 时 -
广告