JS获取和监听屏幕方向变化

本文介绍了三种JavaScript方法来获取和监听移动设备的屏幕方向变化。方法一使用matchMedia监听orientation属性,方法二通过orientationChange事件,方法三依赖resize事件结合innerWidth和innerHeight判断。当某些设备不支持orientationchange事件或media queries时,可以利用resize事件来识别屏幕方向。

移动设备的屏幕有两个方向: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
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值