JS检测移动端横竖屏

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS检测移动端横竖屏相关的知识,希望对你有一定的参考价值。

 (function () {
                                var supportOrientation = (typeof window.orientation === ‘number‘ &&
                                typeof window.onorientationchange === ‘object‘);
                                var init = function () {
                                    var htmlNode = document.body.parentNode,
                                    orientation;
                                    var updateOrientation = function () {
                                        if (supportOrientation) {
                                            orientation = window.orientation;
                                            switch (orientation) {
                                                case 90:
                                                case -90:
                                                    orientation = ‘landscape‘; //这里是横屏
                                                    //alert("横屏");
                                                    break;
                                                default:
                                                    orientation = ‘portrait‘;//这里是竖屏
                                                    //alert("竖屏");
                                                    break;
                                            }
                                        } else {
                                            orientation = (window.innerWidth > window.innerHeight) ? ‘landscape‘ : ‘portrait‘;
                                        }
                                        htmlNode.setAttribute(‘class‘, orientation);
                                    };
                                    if (supportOrientation) {
                                        // 每次旋转,调用这个事件。
                                        window.addEventListener(‘orientationchange‘, updateOrientation, false);
                                    } else {
                                        //监听resize事件
                                        window.addEventListener(‘resize‘, updateOrientation, false);
                                    }
                                    updateOrientation();
                                };
                                window.addEventListener(‘DOMContentLoaded‘, init, false);
                            })();

 

 

 来源:http://www.jb51.net/article/85438.htm




































以上是关于JS检测移动端横竖屏的主要内容,如果未能解决你的问题,请参考以下文章

移动端判断手机横竖屏状态

移动端--判断横竖屏

检测手机横竖屏切换

JavaScript 监听移动端横竖屏状态的几种方式

JavaScript 监听移动端横竖屏状态的几种方式

移动端fixed后 横竖屏切换时上不或下部下部出现空隙问题