我使用了.js来避免从移动设备上查看风景。我编辑了一张白色的全屏图像,上面写着“我认为该网站不宜以横向模式观看,请打开设备”,这是我每次将设备从纵向旋转到横向时都显示的。
除加载页面且已处于横向模式外,它均有效。关于如何解决它的任何想法?谢谢

<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>

更新:

我尝试将window.orientation添加到脚本中,但是出了点问题
if (orientation === "landscape-primary") {
    doOnOrientationChange();
    window.addEventListener('resize',doOnOrientationChange,'false');
}

window.onload(doOnOrientationChange());

最佳答案

您需要将doOnOrientationChange()函数移到另一个函数之外,然后在pageload上调用它。这样它应该工作:

<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>

关于javascript - JavaScript doOnOrientationChange:无法修复加载页面的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30562945/

10-09 14:50