Javascript doOnOrientationChange :can't fix a

2019-03-01 10:55发布

I used a .js to avoid landscape view from mobile device. I edited a white full-screen image saying "this site is not thought to be viewed in landscape mode, please turn your device" to be shown each time I rotate my device from portrait to landscape. It works except when I load a page and I'm already in landscape mode. Any idea on how to fix it? Thanks

<script>
(function() {
    'use strict';

    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if (isMobile.any()) {
        doOnOrientationChange();
        window.addEventListener('resize', doOnOrientationChange, 'false');
    }

    function doOnOrientationChange() {
        var a = document.getElementById('alert');
        var b = document.body;
        var w = b.offsetWidth;
        var h = b.offsetHeight;
        (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
    }
})();
</script>

Update :

I tried adding window.orientation to the script but something is wrong

if (orientation === "landscape-primary") {
    doOnOrientationChange();
    window.addEventListener('resize',doOnOrientationChange,'false');
}

window.onload(doOnOrientationChange());

1条回答
神经病院院长
2楼-- · 2019-03-01 11:52

You need to move the doOnOrientationChange() function outside of the other one, and then call it on pageload. Like this it should work:

<script>
function checkMobile() {
    var isMobile = false;
    if (navigator.userAgent.match(/Android/i)
     || navigator.userAgent.match(/BlackBerry/i)
     || navigator.userAgent.match(/iPhone|iPad|iPod/i)
     || navigator.userAgent.match(/Opera Mini/i)
     || navigator.userAgent.match(/IEMobile/i)) {
            isMobile = true;
        }
    return isMobile;
}
function doOnOrientationChange() {
    var a = document.getElementById('alert');
    var b = document.body;
    var w = b.offsetWidth;
    var h = b.offsetHeight;
    if (checkMobile()) {
        (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
    } else {
        a.className = 'hide';
        b.className = '';
    }
}
window.onload = doOnOrientationChange();
window.addEventListener('resize', doOnOrientationChange, 'false');
</script>
查看更多
登录 后发表回答