isOrientation = ('orientation' in window && 'onorientationchange' in window); 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'; 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