使用 javascript 在 Android 中更改方向

2024-04-17

document.addEventListener("orientationChanged", updateOrientation);

我正在尝试调用一个函数updateOrientation,但该函数只是没有被调用。我正在使用 javascript 代码来实现同样的目的。

谁能帮我orientationChange使用 JavaScript 代码。

提前致谢。


这并不容易:我也玩过很多次:)

首先,您可能已经注意到,某些 Android 设备(例如三星 Galaxy Tab)在横向时会被检测为纵向,反之亦然。因此,首先您需要构建函数来检测基于 screen.width 和 screen.height 的方向(如果未检测到 ipad)(ipad 将始终正确显示方向.. 无论如何,我对此并不感兴趣)。

然后,您必须在一段时间检测到方向变化并超时后触发回调函数,以使整个环境根据新方向相应变化。

所以这就是我的做法..很高兴分享:)

function orientation_changed ()
{
    if ( is_portrait() )
    {
        //do something
    }
    else if ( is_landscape() )
    {
        // do something else
    }
    clearTimeout(window.t);
    delete window.t;
}

window.t = undefined;
window.onorientationchange = function (event)
{
    window.t = setTimeout('orientation_changed();', 250);
}

function is_landscape()
{
    var uagent = navigator.userAgent.toLowerCase();
    if ( uagent.search('ipad') > -1 )
    {
        var r = ( window.orientation == 90 || window.orientation == -90 );
    }
    else
    {
        var r = ( screen.width > screen.height );
    }
    return r;
}

function is_portrait()
{
    var uagent = navigator.userAgent.toLowerCase();
    if ( uagent.search('ipad') > -1 )
    {
        var r = ( window.orientation == 0 || window.orientation == 180 );
    }
    else
    {
        var r = ( screen.width < screen.height );
    }
    return r;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 javascript 在 Android 中更改方向 的相关文章

随机推荐