AI编程助手
AI免费问答

html5 - 怎样在手机网页中判断当前是横屏或者竖屏?

现在需要在手机横竖屏的时候显示的网页的布局是不一样的。现行的解决方案是监听window的onresize事件,然后判断当前屏幕的宽高比。但是使用的过程中遇到两个问题:
1.如果你弹出输入法进行输入的时候,onresize事件也会触发的,但是这个时候如果处在竖屏下,获取出来的屏幕宽很有可能是比屏幕高要大的,这个时候得出的结果很明显是错误的。
2.在UC浏览器下获取的宽高不准确。

# HTML
大家讲道理 大家讲道理 2984 天前 951 次浏览

全部回复(3) 我要回复

  • ringa_lee

    ringa_lee2017-04-17 11:23:31

    可以使用css3 的媒体查询来实现

    @media screen and (orientation:portrait) {
        /*  css[竖向定义样式]  */
        ......
    }
    
    @media screen and (orientation:landscape) {
        /*   css[横向定义样式]  */
        ......
    
    }
    

    回复
    0
  • PHPz

    PHPz2017-04-17 11:23:31

    监听 window 的 orientationchange 事件

    javascriptwindow.addEventListener('orientationchange', function(event){
        if ( window.orientation == 180 || window.orientation==0 ) {
            alert("竖屏");
        }
        if( window.orientation == 90 || window.orientation == -90 ) {
            alert("横屏");
        }
    });
    

    回复
    0
  • 怪我咯

    怪我咯2017-04-17 11:23:31

    var utilResize = {
            init : function() {
                var ua = navigator.userAgent.toLowerCase();
                this.isIos = (/(iphone|ipad|ipod)/i).test(ua);
    
                this.canUseNativeFullApi = (/(qqbrowser|ucbrowser|micromessenger)/i).test(ua);
                this.isModenBrowser = this.isIos | this.canUseNativeFullApi;//高级浏览器横竖屏监听重力感应事件
            }
            addOrientationListener : function() {
                var self = this;
    
                if (this.isModenBrowser) {console.log('use orientationchange');
                    window.addEventListener('orientationchange', function(){
                        self._orientationChangeHandler();
                    });
                } else {console.log('use resize event');
                    $(window).resize(function() {
                        self._orientationChangeHandler();
                    });
                }
            },
            _orientationChangeHandler : function() {
                var self = this;
                setTimeout(function() {
                    if ( window.orientation == 180 || window.orientation== 0 ) {
                        onsole.log('竖屏');////
                    } else if( window.orientation == 90 || window.orientation == -90 ) {//横屏
                        
                    }
                    
                }, 300);
            }
    }

    这是我最后的解决方案

    回复
    0
  • 取消 回复 发送