js判断横竖屏及监听事件
2020-5-3 zhulinan JavaScript
方法一:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js判断横竖屏及监听事件</title>
</head>
<body>
<p></p>
<script>
var para = document.querySelector('p');
var screenDirection = window.matchMedia("(orientation: portrait)");
screenDirection.addListener(handleOrientationChange);
handleOrientationChange(screenDirection);
function handleOrientationChange(screenDirection) {
if (screenDirection.matches) {
para.textContent = '竖屏';
} else {
para.textContent = '横屏';
}
}
</script>
</body>
</html>
方法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js判断横竖屏及监听事件</title>
</head>
<body>
<p></p>
<script>
var para = document.querySelector('p');
function readDeviceOrientation() {
if (Math.abs(window.orientation) === 90) {
para.textContent = '横屏';
} else {
para.textContent = '竖屏';
}
}
window.onorientationchange = readDeviceOrientation;
readDeviceOrientation();
</script>
</body>
</html>
在华为手机浏览器和微信测试2种方法均正确,在PC浏览器上(仅横屏)测试方法二不正确。