在 H5 页面中,可以通过以下几种方法判断当前设备是横屏还是竖屏:
方法一:使用 window.orientation
window.orientation 属性返回当前设备的旋转角度。常见的值有:
0 或 180 表示竖屏90 或 -90 表示横屏
function isLandscape() {
return window.orientation === 90 || window.orientation === -90;
}
if (isLandscape()) {
console.log('当前是横屏');
} else {
console.log('当前是竖屏');
}
方法二:使用 window.matchMedia
window.matchMedia 方法可以用来检测媒体查询的结果。你可以使用媒体查询来判断设备的方向。
function isLandscape() {
return window.matchMedia("(orientation: landscape)").matches;
}
if (isLandscape()) {
console.log('当前是横屏');
} else {
console.log('当前是竖屏');
}
方法三:使用 screen.orientation
screen.orientation 属性返回一个包含屏幕方向信息的对象。你可以通过 screen.orientation.type 来判断当前的屏幕方向。
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
const containerSize = useSize(ref);
useEffect(() => {
// 如果宽度大于高度,就表示是在横屏状态
if ((containerSize?.width ?? 0) > (containerSize?.height ?? 1)) {
console.log("横屏状态");
} else {
console.log("竖屏状态");
}
}, [containerSize?.height, containerSize?.width]);
return (
style={{
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
}}
ref={ref}
>
你的内容
);
};
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 (
{isLandscape ? '当前是横屏' : '当前是竖屏'}
);
};
export default OrientationChecker;
解释
useState:
创建一个状态变量 isLandscape,用于存储当前屏幕方向。
handleOrientationChange:
定义一个函数,用于更新屏幕方向状态。
useEffect:
在组件挂载时添加 orientationchange 和 resize 事件监听器。在组件卸载时清理事件监听器。
通过这些方法,你可以在 H5 页面中判断当前是横屏还是竖屏,并在屏幕方向变化时执行相应的操作。
