簡體   English   中英

使用JavaScript檢測瀏覽器中Android手機的旋轉

[英]Detect rotation of Android phone in the browser with JavaScript

我知道在iPhone上的Safari中,你可以通過監聽onorientationchange事件和查詢window.orientation來檢測屏幕的方向和方向的變化。

這可能在Android手機上的瀏覽器中出現嗎?

為了清楚起見,我問的是,在標准網頁上運行的JavaScript是否可以檢測到Android設備的旋轉。 這可能在iPhone上,我想知道是否可以為Android手機完成。

跨不同設備的實際行為是不一致的 resize和orientationChange事件可以以不同的頻率以不同的順序觸發。 此外,某些值(例如screen.width和window.orientation)並不總是在您預期時更改。 避免使用screen.width - 在iOS中旋轉時不會改變。

可靠的方法是監聽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);

以下是我測試的四個設備的結果(對於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          |
|----------------+-------------------+-------------+------------+--------------|

要在Android瀏覽器上檢測方向更改,請將偵聽器附加到window上的orientationchangeresize事件:

// 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);

檢查window.orientation屬性以確定設備的方向。 使用Android手機時, screen.widthscreen.height也會隨着設備的旋轉而更新。 (這不是iPhone的情況)。

兩位傻瓜的優秀答案提供了所有背景,但讓我嘗試一下簡明實用的總結,介紹如何在iOS和Android上處理方向變化

  • 如果您只關心窗口尺寸 (典型情況) - 而不是特定方向:
    • 僅處理resize事件。
    • 在處理程序中,僅對window.innerWidthwindow.InnerHeight
    • 不要使用window.orientation - 它不會是最新的iOS。
  • 如果您關心具體方向
    • 處理Android上的resize事件, 處理iOS上的orientationchange事件。
    • 在你的處理程序中,作用於window.orientation (和window.innerWidthwindow.InnerHeight

這些方法比記住以前的方向和比較提供了一些好處:

  • 僅在尺寸方法上也可以在桌面瀏覽器上進行開發,否則可以模擬移動設備,例如Chrome 23.(桌面瀏覽器上不提供window.orientation )。
  • 不需要全局/匿名文件級函數包裝級變量。

您可以隨時收聽窗口調整大小事件。 如果,在那個事件中,窗口從高寬度變寬到寬度高(反之亦然),你可以非常確定手機方向剛剛改變。

我有同樣的問題。 我正在使用Phonegap和Jquery移動設備,用於Adroid設備。 要正確調整大小,我必須設置超時:

$(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);
}

它可以在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);

它還支持deskop瀏覽器,但它總是返回相同的值。

這是解決方案:

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");
            }   
        });
    }

您可以嘗試解決方案,與所有瀏覽器兼容。

以下是orientationchange兼容性pic: 兼容性 因此,我創作了一個orientaionchange ,它基於@media屬性來修復orientationchange實用程序庫 - orientationchange-fix

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

另一個問題 - 一些Android平板電腦(摩托羅拉Xoom我相信和一個低端的Elonex我正在進行一些測試,可能還有其他一些)安裝了加速度計,以便在LANDSCAPE模式下window.orientation == 0,而不是肖像!

跨瀏覽器方式

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

值得注意的是,在我的Epic 4G Touch上,我必須設置webview以在任何javascript android調用工作之前使用WebChromeClient。

webView.setWebChromeClient(new WebChromeClient());

這個兩位傻瓜的回答有點貢獻:

正如droid手機上的表所述,“orientationchange”事件比“resize”事件更早被觸發,因此阻止了下一次調整大小調用(因為if語句)。 寬度屬性仍未設置。

一個解決方法雖然可能不是一個完美的可能是不會觸發“orientationchange”事件。 這可以通過在“if”語句中包裝“orientationchange”事件綁定來存檔:

if (!navigator.userAgent.match(/android/i))
{
    window.addEventListener("orientationchange", checkOrientation, false);
}

希望能幫助到你

(在Nexus S上進行了測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM