更靠谱的横竖屏检测方法

2016-09-12 21:59:03 +08:00
 zhansingsong

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

方案一:

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

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

如下是orientationchange事件的兼容性:

如下是screen.orientation的兼容性:

方案二:

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

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

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

关键代码如下:

    var resizeCB = function(){
      if(win.innerWidth > win.innerHeight){//初始化判断
        meta.init = 'landscape';
        meta.current = 'landscape';
      } else {
        meta.init = 'portrait';
        meta.current = 'portrait';
      }
      return function(){
        if(win.innerWidth > win.innerHeight){
          if(meta.current !== 'landscape'){
            meta.current = 'landscape';
            event.trigger('__orientationChange__', meta);
          }
        } else {
          if(meta.current !== 'portrait'){
            meta.current = 'portrait';
            event.trigger('__orientationChange__', meta);
          }
        }
      }
    }();

完整代码猛击这里

方案三:

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

如下@media兼容性: 如上上图所示,移动端浏览器都支持 CSS3 media 。

实现思路:

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

  • 优先使用排在前面的字体。
  • 如果找不到该种字体,或者该种字体不包括所要渲染的文字,则使用下一种字体。
  • 如果所列出的字体,都无法满足需要,则让操作系统自行决定使用哪种字体。

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

关键代码如下:

    // callback
    var resizeCB = function() {
        var hstyle = win.getComputedStyle(html, null),
            ffstr = hstyle['font-family'],
            pstr = "portrait, " + ffstr,
            lstr = "landscape, " + ffstr,
            // 拼接 css
            cssstr = '@media (orientation: portrait) { .orientation{font-family:' + pstr + ';} } @media (orientation: landscape) {  .orientation{font-family:' + lstr + ';}}';
        // 载入样式		
        loadStyleString(cssstr);
        // 添加类
        html.className = 'orientation' + html.className;
        if (hstyle['font-family'] === pstr) { //初始化判断
            meta.init = 'portrait';
            meta.current = 'portrait';
        } else {
            meta.init = 'landscape';
            meta.current = 'landscape';
        }
        return function() {
            if (hstyle['font-family'] === pstr) {
                if (meta.current !== 'portrait') {
                    meta.current = 'portrait';
                    event.trigger('__orientationChange__', meta);
                }
            } else {
                if (meta.current !== 'landscape') {
                    meta.current = 'landscape';
                    event.trigger('__orientationChange__', meta);
                }
            }
        }
    }();

完整代码猛击这里

测试效果

方案四:

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

关键代码如下:

// 是否支持 orientationchange 事件
var isOrientation = ('orientation' in window && 'onorientationchange' in window);
// callback
var orientationCB = function(e) {
    if (win.orientation === 180 || win.orientation === 0) {
        meta.init = 'portrait';
        meta.current = 'portrait';
    }
    if (win.orientation === 90 || win.orientation === -90) {
        meta.init = 'landscape';
        meta.current = 'landscape';
    }
    return function() {
        if (win.orientation === 180 || win.orientation === 0) {
            meta.current = 'portrait';
        }
        if (win.orientation === 90 || win.orientation === -90) {
            meta.current = 'landscape';
        }
        event.trigger(eventType, meta);
    }
};
var callback = isOrientation ? orientationCB() : (function() {
    resizeCB();
    return function() {
        timer && win.clearTimeout(timer);
        timer = win.setTimeout(resizeCB, 300);
    }
})();
// 监听
win.addEventListener(isOrientation ? eventType : 'resize', callback, false);

完整代码猛击这里

方案五:

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

关键代码如下:

var eventType = 'orientationchange';
// 触发原生 orientationchange
var fire = function() {
    var e;
    if (document.createEvent) {
        e = document.createEvent('HTMLEvents');
        e.initEvent(eventType, true, false);
        win.dispatchEvent(e);
    } else {
        e = document.createEventObject();
        e.eventType = eventType;
        if (win[eventType]) {
            win[eventType]();
        } else if (win['on' + eventType]) {
            win['on' + eventType]();
        } else {
            win.fireEvent(eventType, e);
        }
    }
}

完整代码猛击这里

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

2683 次点击
所在节点    JavaScript
7 条回复
hasbug
2016-09-12 22:25:43 +08:00
感谢分享!
yushiro
2016-09-13 00:10:04 +08:00
内容很有帮助,但每个方案一步一步更完美的迭代更有教育意义
ljbha007
2016-09-13 00:24:42 +08:00
其实靠宽高比判断就够了 因为你知道横竖屏的最终目的也是为了知道宽高比而已
iTakeo
2016-09-13 08:50:08 +08:00
其实 css 那个判断也是判断的宽高比
zhansingsong
2016-09-13 10:28:16 +08:00
@iTakeo 没有深入了解 @media 判断机制,了解测试了一下,确实是:)
zhansingsong
2016-09-13 10:32:08 +08:00
@iTakeo 不过在获取高宽时,某些浏览器给出的值不太正确,相当╮(╯_╰)╭
doublleft
2016-09-13 14:45:17 +08:00
一样的啊,支持 orientation 的设备同时也会支持 media query ,反之同理

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/305792

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX