运行 ❯
获取您
自己的
网站
×
更改方向
保存代码
更改主题,暗/亮
前往 Spaces
<!DOCTYPE html> <html> <body> <h1>The Window Object</h1> <h2>The matchMedia() Method</h2> <p>If the viewport is less or equal to 500 pixels wide, set background to yellow, otherwise to pink.</p> <p>Resize the browser window to see the effect.</p> <script> // 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); }); </script> </body> </html>