2016-01-13 77 views
1

我需要使用JavaScript來獲取我的科爾多瓦android應用程序的窗口的寬度和高度。Cordova:如何獲得應用程序的寬度和高度?

我試圖從$(window).width() and $(window).height() jQuery庫,但結果是喜怒無常:

我測試在Nexus 7,當我在縱向模式下打開的應用程序,我得到寬度= 600,高度= 888

當我旋轉設備,以景觀和重新計算的尺寸不改變的時候,他們應該換,當我旋轉設備來備份到人像我得到寬度= 960,高度= 528

我很迷茫通過這個輸出,它讓我覺得我使用了錯誤的代碼。我會非常感謝您的幫助或建議。

這裏是用於獲取屏幕尺寸的功能:

function getDimensions() { 
    //Gets height and width of web browser 
    var height = $(window).height(); 
    var width = $(window).width(); 

    //Stores dimensions in array of form [width,height] 
    var dimensions = [width,height]; 

    return dimensions; 
} 

這裏就是我檢查尺寸旋轉後:

function onOrientationChange() { 
    var dimensions = getDimensions(); 
    console.log("rotation width " + dimensions[0] + " height " + dimensions[1]); 
} 
+1

你能發佈您的代碼嗎? – erikscandola

+0

我編輯過,以包含我的getDimensions()函數 – shakety

+0

聽起來就像您在重繪出現之前計算寬度和高度,導致旋轉之前窗口的寬度和高度。旋轉後如何檢測窗口重繪?*編輯*:您是否嘗試在定向事件發生後使用setTimeout在回調中進行檢查? – Samsinite

回答

0

嘗試: 變種W = window.innerWidth; var h = window.innerHeight; 我知道這個工程上的Web瀏覽器

+0

這給出了與上面的代碼相同的響應 – shakety

0

你必須與orientationchange事件工作:

當設備的方向已經改變orientationChange事件被觸發。

而且包含代表當前方位(查看下面有詳細介紹圖片)了一批Window.orientation財產。

window.orientation values

通知!:window.orientation在桌面瀏覽器中返回undefined。所以請在模擬器或設備上測試。

解決方案:

  1. 附加orientationchange事件的全局窗口對象。
  2. 檢查方向值並在那裏做一些邏輯。

window.addEventListener("orientationchange", orientationChange); 
 

 
function orientationChange() { 
 
    switch (window.screen.orientation) { 
 
    case "landscape-primary": 
 
     //your function over here: getDimensions(); 
 
     break; 
 
    case "portrait-primary": 
 
     //your function over here: getDimensions(); 
 
     break; 
 
    default: 
 
     break; 
 
    } 
 
}

+0

我對設備方向不感興趣。我只想知道尺寸。 – shakety

+0

您寫下了這篇文章:「當我將設備旋轉到橫向並重新計算它們應該交換時它們不會改變的尺寸,並且當我將設備旋轉回縱向時,我得到width = 960,height = 528。」 –

+0

你必須檢查每個方向變化的尺寸以獲得正確的值 –

相關問題