我正在尝试获取 iOS 的当前屏幕方向,但是我的功能可以在 chrome 开发工具模拟器和桌面上运行,但在 iOS 上不起作用。
这是我的功能:
export type ScreenOrientation = "landscape" | "portrait";
export function getScreenOrientation(): ScreenOrientation
{
if (window.screen.availHeight > window.screen.availWidth)
return "portrait";
else
return "landscape";
}
这是我的程序大致如何检测屏幕方向变化并使用该功能:
import { getScreenOrientation } from "../../Utils/getOrientation";
const shoWPortraitModeError = getScreenOrientation() == "landscape" ? false : true;
window.onorientationchange = function () {
const newState = getScreenOrientation() == "landscape" ? false : true;
console.log("window.onorientationchange: ", newState)
shoWPortraitModeError = newState;
};
我尝试使用
window.screen.height
和 window.screen.width
但没有成功。这是函数:
export type ScreenOrientation = "landscape" | "portrait";
export function getScreenOrientation(): ScreenOrientation
{
if (window.screen.availHeight > window.screen.availWidth)
return "portrait";
else
return "landscape";
}
我在 mac 虚拟机上启动 iOS safari 调试器,我注意到当我转动屏幕时
window.screen
值没有改变:
这让我想知道我可以使用哪些不同的属性来检测 ios 上的屏幕方向?
在 safari 调试器的开发控制台的 intelisense 中进行深入研究后,我发现您可以使用
window.innerHeight
和 window.innerWidth
属性来检测屏幕方向。
以下是如何使用该功能:
export type ScreenOrientation = "landscape" | "portrait";
export function getScreenOrientation(): ScreenOrientation
{
if (window.innerHeight > window.innerWidth)
return "portrait";
else
return "landscape";
}
如果你想做一些CSS,你可以使用媒体查询。
https://developer.mozilla.org/en-US/docs/Web/CSS/@media/orientation
基本上可以用
@media (orientation: landscape) {}
如果你想在JS中使用,出于其他目的,你可以使用:
let orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;
if (orientation === "landscape-primary") {
console.log("That looks good.");
} else if (orientation === "landscape-secondary") {
console.log("Mmmh... the screen is upside down!");
} else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
console.log("Mmmh... you should rotate your device to landscape");
} else if (orientation === undefined) {
console.log("The orientation API isn't supported in this browser :(");
}
尽管已被弃用,但它适用于 iOS 16 Safari(2022 年末):
// rotate right
window.orientation // -90
// rotate left
window.orientation // 90
我目前(2023 年初)使用这条小线返回方向角度,我可以自己解释:
let orientation = (screen.orientation.angle || window.orientation);
0以外的值表示不是纵向,90表示反向纵向。
您可以使用window.matchMedia
const landscapeQuery = window.matchMedia('(orientation: landscape)');
function handleOrientationChange(mediaQuery) {
if (mediaQuery.matches) {
console.log('Device is in landscape mode');
} else {
console.log('Device is in portrait mode');
}
}
landscapeQuery.addListener(handleOrientationChange);
handleOrientationChange(landscapeQuery); // Initial check