shimily

移动设备的屏幕有两个方向: landscape(横屏)和portrait(竖屏),在某些情况下需要获取设备的屏幕方向和监听屏幕方向的变化,因此可以使用Javascript提供的 MediaQueryList 对象接口,使用方法如下:

获取当前屏幕方向(是否是竖屏状态)

var mql = window.matchMedia("(orientation: portrait)");

打印mql,得到MediaQueryList对象如下:

可以通过访问对象的 matches 属性来查看查询结果:

1 if(mql.matches) {
2     console.log(\'portrait\');   // 竖屏
3 }else {
4     console.log(\'landscape\');  // 横屏
5 }

监听屏幕方向变化,可以通过 MediaQueryList 对象的 addListener 方法来订阅事件,如下;

复制代码
 1 var mql = window.matchMedia(\'(orientation: portrait)\');
 2 console.log(mql);
 3 function handleOrientationChange(mql) {
 4     if(mql.matches) {
 5         console.log(\'portrait\');  // 竖屏
 6     }else {
 7         console.log(\'landscape\'); // 横屏
 8     }
 9 }
10 // 输出当前屏幕模式
11 handleOrientationChange(mql);
12 // 监听屏幕模式变化
13 mql.addListener(handleOrientationChange);
复制代码

在浏览器中运行代码,并在手机模式下改变屏幕方向,在控制台中得到打印结果如下:

从结果可以知道,屏幕方向从原来的竖屏变成了横屏。

最后,移除订阅者的方法如下:

mql.removeListener(handleOrientationChange);

分类:

技术点:

相关文章:

  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
  • 2021-06-12
  • 2021-06-18
  • 2021-12-14
  • 2021-11-27
猜你喜欢
  • 2021-06-04
  • 2021-06-20
  • 2022-12-23
  • 2021-10-15
  • 2021-05-18
  • 2021-05-18
相关资源
相似解决方案