更靠谱的移动端横竖屏检测方法

移动开发 移动应用
前不久,做了一个H5项目,需要在横竖屏变化时,做一些处理。毫无疑问,需要使用orientationchange来监听横竖屏的变化。

[[171604]]

前不久,做了一个H5项目,需要在横竖屏变化时,做一些处理。毫无疑问,需要使用orientationchange来监听横竖屏的变化。

方案一:

  1. // 监听 orientation changes 
  2. window.addEventListener("orientationchange"function(event) { 
  3.     // 根据event.orientation|screen.orientation.angle等于0|180、90|-90度来判断横竖屏 
  4. }, false);  

代码添加上后,就各种兼容性问题。这里兼容性问题出现在两个地方:

  • orientationchange
  • event.orientation|screen.orientation.angle

如下是orientationchange事件的兼容性:

 如下是screen.orientation的兼容性:

 方案二:

上述方案不行,只能另行他法了。google一下,了解到可以通过resize配合(window.inner/outerWidth, window.inner/outerHeight)来实现:

  1. window.addEventListener("resize"function(event) { 
  2.     var orientation=(window.innerWidth > window.innerHeight)? "landscape":"portrait"
  3.     if(oritentation === 'portrait'){ 
  4.         // do something …… 
  5.     } else { 
  6.         // do something else …… 
  7.     } 
  8. }, false);  

这种方案基本满足大部分项目的需求,但是还是有些不足之处:

  • 只要window的size变化,就会不断触发触发resize事件。可以使用setTimeout来优化一下
  • 如果有多个地方需要监听横竖屏,就需要注册多个window.addEventListener("resize", function(event) {……})。能不能通过订阅与发布模式来改进一下,只注册一个resize负责监听横竖屏变化,只要横竖发生变化就发布通知订阅的对象。其他需要监听横竖屏的地方只需订阅一下即可。

关键代码如下:

  1. var resizeCB = function(){ 
  2.      if(win.innerWidth > win.innerHeight){//初始化判断 
  3.        meta.init = 'landscape'
  4.        meta.current = 'landscape'
  5.      } else { 
  6.        meta.init = 'portrait'
  7.        meta.current = 'portrait'
  8.      } 
  9.      return function(){ 
  10.        if(win.innerWidth > win.innerHeight){ 
  11.          if(meta.current !== 'landscape'){ 
  12.            meta.current = 'landscape'
  13.            event.trigger('__orientationChange__', meta); 
  14.          } 
  15.        } else { 
  16.          if(meta.current !== 'portrait'){ 
  17.            meta.current = 'portrait'
  18.            event.trigger('__orientationChange__', meta); 
  19.          } 
  20.        } 
  21.      } 
  22.    }();  

完整代码猛击这里

方案三:

不过个人觉得通过window.innerWidth > window.innerHeight来实现的是一种伪检测,有点不可靠。 可不可以通过浏览器来实现检测?如基于CSS3@media媒体查询来实现。

如下@media兼容性:

 如上上图所示,移动端浏览器都支持CSS3 media。

实现思路:

  • 创建包含标识横竖屏状态的特定css样式
  • 通过JS向页面中注入CSS代码
  • resize回调函数中获取横竖屏的状态

这里我选择<html></html>的节点font-family作为检测样式属性。理由如下:

  • 选择<html></html>主要为了避免reflow和repaint
  • 选择font-family样式,主要是因为font-family有如下特性:

1.优先使用排在前面的字体。

2.如果找不到该种字体,或者该种字体不包括所要渲染的文字,则使用下一种字体。

3.如果所列出的字体,都无法满足需要,则让操作系统自行决定使用哪种字体。

这样我们就可以指定特定标识来标识横竖屏的状态,不过需要将指定的标识放置在其他字体的前面,这样就不会引起hmtl字体的变化。

关键代码如下:

  1. // callback 
  2.     var resizeCB = function() { 
  3.         var hstyle = win.getComputedStyle(html, null), 
  4.             ffstr = hstyle['font-family'], 
  5.             pstr = "portrait, " + ffstr, 
  6.             lstr = "landscape, " + ffstr, 
  7.             // 拼接css 
  8.             cssstr = '@media (orientation: portrait) { .orientation{font-family:' + pstr + ';} } @media (orientation: landscape) {  .orientation{font-family:' + lstr + ';}}'
  9.         // 载入样式         
  10.         loadStyleString(cssstr); 
  11.         // 添加类 
  12.         html.className = 'orientation' + html.className; 
  13.         if (hstyle['font-family'] === pstr) { //初始化判断 
  14.             meta.init = 'portrait'
  15.             meta.current = 'portrait'
  16.         } else { 
  17.             meta.init = 'landscape'
  18.             meta.current = 'landscape'
  19.         } 
  20.         return function() { 
  21.             if (hstyle['font-family'] === pstr) { 
  22.                 if (meta.current !== 'portrait') { 
  23.                     meta.current = 'portrait'
  24.                     event.trigger('__orientationChange__', meta); 
  25.                 } 
  26.             } else { 
  27.                 if (meta.current !== 'landscape') { 
  28.                     meta.current = 'landscape'
  29.                     event.trigger('__orientationChange__', meta); 
  30.                 } 
  31.             } 
  32.         } 
  33.     }();  

完整代码猛击这里

测试效果

  • portrait效果:

 

  • landscape效果:

 

方案四:

可以再改进一下,在支持orientationchange时,就使用原生的orientationchange,不支持则使用方案三。

关键代码如下:

  1. // 是否支持orientationchange事件 
  2. var isOrientation = ('orientation' in window && 'onorientationchange' in window); 
  3. // callback 
  4. var orientationCB = function(e) { 
  5.     if (win.orientation === 180 || win.orientation === 0) { 
  6.         meta.init = 'portrait'
  7.         meta.current = 'portrait'
  8.     } 
  9.     if (win.orientation === 90 || win.orientation === -90) { 
  10.         meta.init = 'landscape'
  11.         meta.current = 'landscape'
  12.     } 
  13.     return function() { 
  14.         if (win.orientation === 180 || win.orientation === 0) { 
  15.             meta.current = 'portrait'
  16.         } 
  17.         if (win.orientation === 90 || win.orientation === -90) { 
  18.             meta.current = 'landscape'
  19.         } 
  20.         event.trigger(eventType, meta); 
  21.     } 
  22. }; 
  23. var callback = isOrientation ? orientationCB() : (function() { 
  24.     resizeCB(); 
  25.     return function() { 
  26.         timer && win.clearTimeout(timer); 
  27.         timer = win.setTimeout(resizeCB, 300); 
  28.     } 
  29. })(); 
  30. // 监听 
  31. win.addEventListener(isOrientation ? eventType : 'resize', callback, false);  

完整代码猛击这里

方案五:

目前,上述几种方案都是通过自定制的订阅与发布事件模式来实现的。这里可以基于浏览器的事件机制,来模拟orientationchange。即对orientationchange的不兼容进行修复。

关键代码如下:

  1. var eventType = 'orientationchange'
  2. // 触发原生orientationchange 
  3. var fire = function() { 
  4.     var e; 
  5.     if (document.createEvent) { 
  6.         e = document.createEvent('HTMLEvents'); 
  7.         e.initEvent(eventType, truefalse); 
  8.         win.dispatchEvent(e); 
  9.     } else { 
  10.         e = document.createEventObject(); 
  11.         e.eventType = eventType; 
  12.         if (win[eventType]) { 
  13.             win[eventType](); 
  14.         } else if (win['on' + eventType]) { 
  15.             win['on' + eventType](); 
  16.         } else { 
  17.             win.fireEvent(eventType, e); 
  18.         } 
  19.     } 
  20.  

完整代码猛击这里

通过上述5种方案,自己对移动端横竖屏检测有了更进一步的认识,有些东西只有自己亲身经历过才知道为什么要这么写,自己也把其中缘由记录在文章中,希望对大家有帮助。经过5种方案的演变得到了最终orientationchange-fix,github地址:https://github.com/zhansingsong/orientationchange-fix

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2013-01-18 10:16:42

2015-11-09 16:45:14

尼泊尔地震

2015-07-23 14:25:04

宕机云主机云智慧

2018-06-01 16:06:29

PR靠谱Code Review

2021-04-01 14:35:08

XDR微步在线

2012-10-22 11:14:05

SDNOpenFlow网络管理

2022-12-01 08:30:10

JavaScript构造函数

2020-12-22 06:18:47

Windows 10Windows操作系统

2013-05-23 10:51:28

Android开发移动开发横竖屏切换

2022-10-18 16:03:38

JS判断数组面试

2018-01-25 16:00:31

2012-06-06 09:07:46

云计算微软

2014-07-29 09:33:17

公司邮箱

2017-07-25 09:55:10

iOS横竖屏旋转

2013-08-21 11:15:54

iOS横竖屏方案

2014-02-19 10:49:55

Windows 9

2011-12-22 09:32:34

虚拟化桌面虚拟化云计算

2017-10-31 11:27:14

宽带百兆光纤移动

2020-06-22 11:30:38

密码数据泄露黑客

2012-05-22 14:26:15

XNA 横竖屏设置
点赞
收藏

51CTO技术栈公众号