【问题标题】:Orientation change in Android using javascript使用javascript在Android中更改方向
【发布时间】:2012-01-24 11:11:08
【问题描述】:
document.addEventListener("orientationChanged", updateOrientation);

我试图在updateOrientation 上调用一个函数,但该函数没有被调用。我正在使用相同的 javascript 代码。

谁能帮助我使用 javascript 代码orientationChange

提前致谢。

【问题讨论】:

  • 如果事件名称是orientationChange,为什么你的代码中有orientationChanged
  • 实际上,事件名称中的所有字母都应该小写
  • @Dan 这不是真的:camelCase 总是允许有一个人类更易读的代码

标签: javascript android cordova


【解决方案1】:

这并不容易:我也经常玩它 :)

首先,您可能已经注意到,一些安卓设备(例如三星 Galaxy Tab)会被检测为纵向,而它们是横向的,反之亦然。因此,如果未检测到 ipad,首先您需要构建基于 screen.width 和 screen.height 检测方向的函数(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;
}

【讨论】:

  • 我在 T-Mobile Galaxy S 上运行 Android 2.2 并且切换了横向/纵向检测。
  • @Zorayr 是的,在 Galaxy 上它们已切换。上面的脚本应该修复它(我在 Galaxy S Tab 上测试过),如果您的意思是它们仍然使用上面的脚本切换,请尝试通过将 250 更改为更大的数字来使用更长的超时。希望对你有帮助
  • 如果使用onresive事件,你不会等待250毫秒
  • @Dan 需要超时以确保所有设备都更新窗口和屏幕的属性。在许多旧的 android 设备上更新事件之前检测到事件。使用 onorientationchange 事件或 onresize 事件的目的没有区别。
【解决方案2】:

要测试原生“orientationchange”支持,请使用"orientationchange" in window

作为后备,使用onresize 事件并检查window.outerHeight &gt; window.outerWidth

【讨论】:

  • OP 已经知道这些事件:他/她要求一些有效的 sn-p。
猜你喜欢
  • 2023-04-09
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
相关资源
最近更新 更多