移动端判断横屏竖屏

可能我们在写移动端项目的时候会有要求或者为了更好的体验会做横竖屏检测,以达到更好的用户体验。

// 判断横竖屏
var utils = {
    debounce: function(func,delay){
        var timer = null;
        return function(){
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function(){
                func.apply(context,args);
            },delay);
        }
    }
}
var detectRes = document.getElementById('J_detectRes');
var detectData = document.getElementById('J_detectData');
function detectOrient() {
    var storage = localStorage; // 不一定要使用localStorage,其他存储数据的手段都可以
    var data = storage.getItem('J-recordOrientX');
    var cw = document.documentElement.clientWidth;
    var _Width = 0,
        _Height = 0;
    if(!data) {
        sw = window.screen.width;
        sh = window.screen.height;
        // 2.在某些机型(如华为P9)下出现 srceen.width/height 值交换,所以进行大小值比较判断
        _Width = sw < sh ? sw : sh;
        _Height = sw >= sh ? sw : sh;
        storage.setItem('J-recordOrientX',_Width + ',' + _Height);
    }else {
        var str = data.split(',');
        _Width = str[0];
        _Height = str[1];
    }
    if(cw == _Width) {
        // 竖屏
        return;
    }
    if(cw == _Height){
        // 横屏
        return;
    }
}
// 3.函数去抖处理
window.onresize = utils.debounce(detectOrient,300);
detectOrient();


详细介绍请参考原作者文章 探讨判断横竖屏的最佳实现


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值