使用 JavaScript 在浏览器中检测 Android 手机的旋转

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1649086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:24:32  来源:igfitidea点击:

Detect rotation of Android phone in the browser with JavaScript

javascriptandroidwebkit

提问by philnash

I know that in Safari on an iPhone you can detect the screen's orientation and change of orientation by listening for the onorientationchangeevent and querying window.orientationfor the angle.

我知道在 iPhone 上的 Safari 中,您可以通过监听onorientationchange事件和查询window.orientation角度来检测屏幕的方向和方向的变化。

Is this possible in the browser on Android phones?

这可以在 Android 手机的浏览器中实现吗?

To be clear, I am asking whether the rotation of an Android device can be detected by JavaScriptrunning on a standard web page. It is possible on an iPhone, and I wondered whether it could be done for Android phones.

明确地说,我问的是 Android 设备的旋转是否可以通过运行在标准网页上的JavaScript检测到。在 iPhone 上是可能的,我想知道是否可以在 Android 手机上完成。

回答by two-bit-fool

The actual behavior across different devices is inconsistent. The resize and orientationChange events can fire in a different sequence with varying frequency. Also, some values (e.g. screen.width and window.orientation) don't always change when you expect. Avoid screen.width-- it doesn't change when rotating in iOS.

不同设备的实际行为是不一致的。resize 和orientationChange 事件可以以不同的顺序以不同的频率触发。此外,某些值(例如 screen.width 和 window.orientation)并不总是在您期望的时候发生变化。避免使用 screen.width-- 在 iOS 中旋转时它不会改变。

The reliable approach is to listen to both resize and orientationChange events(with some polling as a safety catch), and you'll eventually get a valid value for the orientation. In my testing, Android devices occasionally fail to fire events when rotating a full 180 degrees, so I've also included a setInterval to poll the orientation.

可靠的方法是同时监听 resize 和orientationChange 事件(使用一些轮询作为安全措施),您最终会得到一个有效的方向值。在我的测试中,Android 设备在旋转完整 180 度时偶尔无法触发事件,因此我还包含了一个 setInterval 来轮询方向。

var previousOrientation = window.orientation;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // orientation changed, do your magic here
    }
};

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);

Here are the results from the four devices that I've tested (sorry for the ASCII table, but it seemed like the easiest way to present the results). Aside from the consistency between the iOS devices, there is a lot of variety across devices. NOTE: The events are listed in the order that they fired.

以下是我测试过的四种设备的结果(对于 ASCII 表很抱歉,但它似乎是呈现结果的最简单方法)。除了 iOS 设备之间的一致性之外,设备之间还有很多变化。注意:事件按它们触发的顺序列出。

|==============================================================================|
|     Device     | Events Fired      | orientation | innerWidth | screen.width |
|==============================================================================|
| iPad 2         | resize            | 0           | 1024       | 768          |
| (to landscape) | orientationchange | 90          | 1024       | 768          |
|----------------+-------------------+-------------+------------+--------------|
| iPad 2         | resize            | 90          | 768        | 768          |
| (to portrait)  | orientationchange | 0           | 768        | 768          |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4       | resize            | 0           | 480        | 320          |
| (to landscape) | orientationchange | 90          | 480        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4       | resize            | 90          | 320        | 320          |
| (to portrait)  | orientationchange | 0           | 320        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone    | orientationchange | 90          | 320        | 320          |
| (to landscape) | resize            | 90          | 569        | 569          |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone    | orientationchange | 0           | 569        | 569          |
| (to portrait)  | resize            | 0           | 320        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 0           | 400        | 400          |
| Tablet         | orientationchange | 90          | 400        | 400          |
| (to landscape) | orientationchange | 90          | 400        | 400          |
|                | resize            | 90          | 683        | 683          |
|                | orientationchange | 90          | 683        | 683          |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 90          | 683        | 683          |
| Tablet         | orientationchange | 0           | 683        | 683          |
| (to portrait)  | orientationchange | 0           | 683        | 683          |
|                | resize            | 0           | 400        | 400          |
|                | orientationchange | 0           | 400        | 400          |
|----------------+-------------------+-------------+------------+--------------|

回答by jb.

To detect an orientation change on an Android browser, attach a listener to the orientationchangeor resizeevent on window:

要检测 Android 浏览器上的方向更改,请将侦听器附加到on的orientationchangeresize事件window

// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation + " " + screen.width);
}, false);

Check the window.orientationproperty to figure out which way the device is oriented. With Android phones, screen.widthor screen.heightalso updates as the device is rotated. (this is not the case with the iPhone).

检查window.orientation属性以确定设备的方向。使用 Android 手机,screen.widthscreen.height随着设备旋转而更新。(iPhone 不是这种情况)。

回答by mklement0

two-bit-fool's excellent answer provides all the background, but let me attempt a concise, pragmatic summary of how to handle orientation changes across iOS and Android:

两位傻瓜的优秀答案提供了所有背景知识,但让我尝试对如何处理 iOS 和 Android 上的方向更改进行简洁实用的总结

  • If you only care about window dimensions(the typical scenario)- and not about the specific orientation:
    • Handle the resizeevent only.
    • In your handler, act on window.innerWidthand window.InnerHeightonly.
    • Do NOT use window.orientation- it won't be current on iOS.
  • 如果您只关心窗口尺寸(典型情况)- 而不是特定方向:
    • resize只处理事件。
    • 在您的处理程序中,仅执行window.innerWidth和执行window.InnerHeight
    • 不要使用window.orientation- 它不会在 iOS 上更新。
  • If you DO care about the specific orientation:
    • Handle onlythe resizeevent on Android, and onlythe orientationchangeevent on iOS.
    • In your handler, act on window.orientation(and window.innerWidthand window.InnerHeight)
  • 如果您确实关心特定方向
    • 处理resizeAndroid 上的事件,orientationchange处理 iOS 上的事件。
    • 在您的处理程序中,对window.orientation(andwindow.innerWidthwindow.InnerHeight)采取行动

These approaches offer slight benefits over remembering the previous orientation and comparing:

与记住以前的方向和比较相比,这些方法提供了一些好处:

  • the dimensions-only approach also works while developing on desktop browsers that can otherwise simulate mobile devices, e.g., Chrome 23. (window.orientationis not available on desktop browsers).
  • no need for a global/anonymous-file-level-function-wrapper-level variable.
  • 仅维度方法也适用于在可以模拟移动设备的桌面浏览器上进行开发,例如 Chrome 23。(window.orientation在桌面浏览器上不可用)。
  • 不需要全局/匿名文件级函数包装级变量。

回答by Joel Mueller

You could always listen to the window resize event. If, on that event, the window went from being taller than it is wide to wider than it is tall (or vice versa), you can be pretty sure the phone orientation was just changed.

您可以随时收听窗口调整大小事件。如果在那个事件中,窗口从高比宽变成比高宽(反之亦然),您可以确定手机方向刚刚改变。

回答by u283863

It is possible in HTML5.
You can read more (and try a live demo) here: http://slides.html5rocks.com/#slide-orientation.

在 HTML5 中是可能的。
您可以在这里阅读更多(并尝试现场演示):http: //slides.html5rocks.com/#slide-orientation

window.addEventListener('deviceorientation', function(event) {
    var a = event.alpha;
    var b = event.beta;
    var g = event.gamma;
}, false);

It also supports deskop browsers but it will always return the same value.

它还支持桌面浏览器,但它总是返回相同的值。

回答by tauanz

I had the same problem. I am using Phonegap and Jquery mobile, for Adroid devices. To resize properly I had to set a timeout:

我有同样的问题。我正在为 Adroid 设备使用 Phonegap 和 Jquery mobile。为了正确调整大小,我必须设置超时:

$(window).bind('orientationchange',function(e) {
  fixOrientation();
});

$(window).bind('resize',function(e) {
  fixOrientation();
});

function fixOrientation() {

    setTimeout(function() {

        var windowWidth = window.innerWidth;

        $('div[data-role="page"]').width(windowWidth);
        $('div[data-role="header"]').width(windowWidth);
        $('div[data-role="content"]').width(windowWidth-30);
        $('div[data-role="footer"]').width(windowWidth);

    },500);
}

回答by Shishir Arora

Here is the solution:

这是解决方案:

var isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent);
    },
    iOS: function() {
        return /iPhone|iPad|iPod/i.test(navigator.userAgent);
    }
};
if(isMobile.Android())
    {
        var previousWidth=$(window).width();
        $(window).on({
        resize: function(e) {
        var YourFunction=(function(){

            var screenWidth=$(window).width();
            if(previousWidth!=screenWidth)
            {
                previousWidth=screenWidth;
                alert("oreientation changed");
            }

        })();

        }
    });

    }
    else//mainly for ios
    {
        $(window).on({
            orientationchange: function(e) {
               alert("orientation changed");
            }   
        });
    }

回答by Zhansingsong

you can try the solution, compatible with all browser.

您可以尝试解决方案,兼容所有浏览器。

Following is orientationchangecompatibility pic: compatibilitytherefore, I author a orientaionchangepolyfill, it is a based on @media attribute to fix orientationchange utility library——orientationchange-fix

以下是orientationchange兼容性图片: 兼容性因此,我编写了一个orientaionchangepolyfill,它是一个基于@media 属性来修复orientationchange 实用程序库——orientationchange -fix

window.addEventListener('orientationchange', function(){
 if(window.neworientation.current === 'portrait|landscape'){
    // do something……
 } else {
    // do something……
 }
}, false);

回答by james-geldart

Another gotcha - some Android tablets (the Motorola Xoom I believe and a low-end Elonex one I'm doing some testing on, probably others too) have their accelerometers set up so that window.orientation == 0 in LANDSCAPE mode, not portrait!

另一个问题 - 一些 Android 平板电脑(我相信是摩托罗拉 Xoom 和我正在做一些测试的低端 Elonex 平板电脑,可能还有其他平板电脑)设置了它们的加速度计,以便 window.orientation == 0 在 LANDSCAPE 模式下,而不是纵向!

回答by comonitos

Cross browser way

跨浏览器方式

$(window).on('resize orientationchange webkitfullscreenchange mozfullscreenchange fullscreenchange',  function(){
//code here
});