判断手机横屏还是竖屏

判断手机方向,第二三种受锁屏影响,指的是文档排布方向

1. 不受锁屏影响

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function maskControl(callback) {
if (!callback) {
console.error('callback is Not Found');
return;
}

let shouldStart = true;

const handleOrientation = ({ gamma, beta }) => {
// 监听手机方向函数多次触发,性能优化
if (!shouldStart) return;
shouldStart = false;
setTimeout(() => {
shouldStart = true;
}, 500);

// 是否隐藏遮罩 (横屏竖屏不是决定的横屏竖屏)
const isHorizontal = ((beta < 20 || beta > -20) && (gamma > 45 || gamma < 0)) || gamma === null;
const isVertical = (gamma > -30 && gamma < 30) || gamma === null;

// 回掉方法
callback({
isHorizontal, isVertical, gamma, beta,
});
};

// 监听手机方向
window.addEventListener('deviceorientation', handleOrientation);
}

2. 受锁屏影响

1
2
3
4
5
6
7
8
window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', () => {
if (window.orientation === 180 || window.orientation === 0) {
//alert('竖屏状态!');
}
if (window.orientation === 90 || window.orientation === -90) {
//alert('横屏状态!');
}
}, false);

3.css媒体查询

1
2
3
4
5
6
7
@media all and (orientation : landscape) { 
<!--横屏-->
}

@media all and (orientation : portrait) {
<!--竖屏-->
}