html5 - 怎样在手机网页中判断当前是横屏或者竖屏?
大家讲道理
大家讲道理 2017-04-17 11:21:31
[HTML讨论组]

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

大家讲道理
大家讲道理

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

全部回复(3)
ringa_lee

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

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

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

}
PHPz

监听 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);
        }
}

这是我最后的解决方案

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号