移动设备的屏幕有两个方向:lanscape 和 portait。
获取当前屏幕方向
方法一:matchMeadia("(orientation: portait)")
const screenDirction = window.matchMedia("(orientation: portrait)");
打印内容

可以通过访问对象的matches属性来查看查询结果:
if (screenDirection.matches) {
console.log('portait');
} else {
console.log('landscape');
}
监听屏幕方向变化,可以通过MediaQueryList对象的addListener方法来订阅事件:
const screenDirection = window.matchMedia("(orientation: portait)");
function listenerOrientationChange(direction) {
if (direction.matches) {
// 坚屏
} else {
// 横屏
}
}
listenerOrientationChange(screenDirection);
screenDirection.addListener(listenerOrientationChange);
最后移除订阅者
screenDirection.removeListener(handleOrientationChange);
方法二: 监听orientationChange 事件
window.orientation 有三个值:0, 90, -90
0为竖屏模式,-90表示该设备横向旋转到右侧的横屏模式 90表示该设备横向旋转到左侧的横屏模式。
有些设备并没有提供orientationchange事件,但不触发窗口的resize事件。并且media queries也不支持的情况下,我们该怎么办呢?
可以用resize事件来判断。用innerWidth , innerHeight,可以检索得到屏幕大小。依据宽和高的大小比较判断,宽小于高为竖屏,宽大与高就是横屏。
代码如下:
updateOrientation() {
var mql = window.matchMedia("(orientation: portrait)");
console.log('updateOrientation: ');
console.log(mql);
let direction = '';
if (supportOrientation) {
direction = window.orientation;
switch (direction) {
case 90:
case -90:
this.screenDirection = 'landscape';
break;
default:
this.screenDirection = 'portrait';
break;
}
} else {
this.screenDirection = (window.innerWidth > window.innerHeight) ? 'landscape' : 'portrait';
}
if (this.screenDirection === 'landscape') {
this.$refs.playerContainer.classList.add('landscape-video');
} else {
this.$refs.playerContainer.classList.remove('landscape-video');
}
};
getScreenDirection() {
if (supportOrientation) {
window.addEventListener('orientationchange', this.updateOrientation, false);
} else {
window.addEventListener('resize', this.updateOrientation, false);
}
};
// 调用
getScreenDirection();
方法三:借助 media queries
@media all and (orientation: portrait) {
// do something
}
@media all and (orientation: landscape) {
// do something
}
本文介绍了三种JavaScript方法来获取和监听移动设备的屏幕方向变化。方法一使用matchMedia监听orientation属性,方法二通过orientationChange事件,方法三依赖resize事件结合innerWidth和innerHeight判断。当某些设备不支持orientationchange事件或media queries时,可以利用resize事件来识别屏幕方向。
1104

被折叠的 条评论
为什么被折叠?



