html5 - 怎样在手机网页中判断当前是横屏或者竖屏?
大家讲道理
大家讲道理 2017-04-17 11:21:31
0
3
430

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

Antworte allen(3)
左手右手慢动作

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

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

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

}
PHPzhong

监听 window 的 orientationchange 事件

javascriptwindow.addEventListener('orientationchange', function(event){
    if ( window.orientation == 180 || window.orientation==0 ) {
        alert("竖屏");
    }
    if( window.orientation == 90 || window.orientation == -90 ) {
        alert("横屏");
    }
});
刘奇
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);
        }
}

这是我最后的解决方案

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!