在 JavaScript 和 CSS 中,有几种方法可以检测屏幕是横屏还是竖屏显示。我将为您介绍两种主要方法:
1. 使用 JavaScript:function checkOrientation() { if (window.matchMedia("(orientation: portrait)").matches) { console.log("当前是竖屏"); // 在这里添加竖屏时的逻辑 } else { console.log("当前是横屏"); // 在这里添加横屏时的逻辑 } } // 初始检查 checkOrientation(); // 监听屏幕方向变化 window.addEventListener("resize", checkOrientation);
这段代码使用 `window.matchMedia()` 方法来检查屏幕方向。它还添加了一个事件监听器来响应屏幕方向的变化。
2. 使用 CSS 媒体查询:/* 竖屏样式 */ @media screen and (orientation: portrait) { body { background-color: lightblue; } } /* 横屏样式 */ @media screen and (orientation: landscape) { body { background-color: lightgreen; } }
这种方法使用 CSS 媒体查询来应用不同的样式,取决于屏幕的方向。
3. 结合 JavaScript 和 CSS:
您可以结合使用这两种方法,例如:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>屏幕方向检测</title> <style> body { transition: background-color 0.3s ease; } @media screen and (orientation: portrait) { body { background-color: lightblue; } } @media screen and (orientation: landscape) { body { background-color: lightgreen; } } </style> </head> <body> <h1 id="orientation-text">屏幕方向: </h1> <script> function checkOrientation() { const isPortrait = window.matchMedia("(orientation: portrait)").matches; const orientationText = document.getElementById("orientation-text"); if (isPortrait) { orientationText.textContent = "屏幕方向: 竖屏"; } else { orientationText.textContent = "屏幕方向: 横屏"; } } // 初始检查 checkOrientation(); // 监听屏幕方向变化 window.addEventListener("resize", checkOrientation); </script> </body> </html>这个例子结合了 CSS 媒体查询和 JavaScript。CSS 负责改变背景颜色,而 JavaScript 则更新页面上的文本内容。
注意事项:
- 在某些设备上,`resize` 事件可能不会在屏幕旋转时触发。在这种情况下,您可以考虑使用 `orientationchange` 事件。
- 某些浏览器可能需要额外的前缀来支持这些特性,特别是在older版本中。网友回复