function isLandscape() {
return window.orientation === 90 || window.orientation === -90;
}
if (isLandscape()) {
console.log('当前是横屏');
} else {
console.log('当前是竖屏');
}
function isLandscape() {
return window.matchMedia("(orientation: landscape)").matches;
}
if (isLandscape()) {
console.log('当前是横屏');
} else {
console.log('当前是竖屏');
}
function isLandscape() {
return screen.orientation.type.startsWith('landscape');
}
if (isLandscape()) {
console.log('当前是横屏');
} else {
console.log('当前是竖屏');
}
你还可以监听屏幕方向的变化,以便在用户旋转设备时执行相应的操作。
function handleOrientationChange() {
if (isLandscape()) {
console.log('当前是横屏');
} else {
console.log('当前是竖屏');
}
}
window.addEventListener('orientationchange', handleOrientationChange);
window.addEventListener('resize', handleOrientationChange);
// 初始判断
handleOrientationChange();
这里使用 ahooks
库的 useSize 实现对元素的宽高监听
import { useSize } from "ahooks";
import { useEffect, useRef } from "react";
/**
* 在主流的移动端设备是高大于宽情况下,监听根元素的宽高严格等于屏幕可视区宽高的元素,可以通过宽高大小或比例来判断是横屏还是竖屏
* @returns
*/
const MyComponent = () => {
const ref = useRef<HTMLDivElement>(null);
const containerSize = useSize(ref);
useEffect(() => {
// 如果宽度大于高度,就表示是在横屏状态
if ((containerSize?.width ?? 0) > (containerSize?.height ?? 1)) {
console.log("横屏状态");
} else {
console.log("竖屏状态");
}
}, [containerSize?.height, containerSize?.width]);
return (
<div
style={{
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
}}
ref={ref}
>
你的内容
</div>
);
};
export default MyComponent;
以下是一个综合示例,展示如何在 React 应用中判断和监听屏幕方向的变化:
import React, { useEffect, useState } from 'react';
const OrientationChecker = () => {
const [isLandscape, setIsLandscape] = useState(window.matchMedia("(orientation: landscape)").matches);
const handleOrientationChange = () => {
setIsLandscape(window.matchMedia("(orientation: landscape)").matches);
};
useEffect(() => {
window.addEventListener('orientationchange', handleOrientationChange);
window.addEventListener('resize', handleOrientationChange);
// 清理事件监听器
return () => {
window.removeEventListener('orientationchange', handleOrientationChange);
window.removeEventListener('resize', handleOrientationChange);
};
}, []);
return (
<div>
{isLandscape ? '当前是横屏' : '当前是竖屏'}
</div>
);
};
export default OrientationChecker;