2014-06-06 20 views
0

使用Android HTML5和Javascript確實令人沮喪。取向改變後獲取真實寬度的Android移動設備

這一次,我試圖找出當前屏幕尺寸(寬)當DOM被加載並當用戶改變方向:

  • screen.width作品在不同的AndroidOS的版本完全不同。不可能使用。
  • jQuery's $(window).width()返回實際寬度,但在方向改變之前觸發。我以200ms的超時時間嘗試過,也不起作用。

然後我嘗試這個片段:

var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height; 

if (navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio) { 
    deviceWidth = deviceWidth/window.devicePixelRatio; 
} 

在某些Android版本也通過定向改變,在有些則沒有。

有什麼建議嗎?

謝謝!

編輯/解決方案:

這就是它是如何工作的,我在Android和iOS:

$(window).on("orientationchange", function(event) { 
    //console.log("This device is in " + event.orientation + " mode!"); 

    var oc_timer; 
    clearTimeout(oc_timer); 
    oc_timer = setTimeout(function() { 
    //do your magic stuff with jQuery's $(window).width() 
    }, 500); 
); 
$(window).orientationchange(); //fire it manually on page load 

回答

0

這梅託德將讓你的設備的尺寸:

Point size = new Point(); 
Display display = getWindowManager().getDefaultDisplay(); 
int height = 0; 
int width = 0; 
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) { 
    display.getSize(size); 
    width = size.x; 
    height = size.y; 
} else { 
    width = display.getWidth(); 
    height = display.getHeight(); 
} 
+0

謝謝,但我需要一個Javascript的解決方案。 – simonhard

1

嘗試它裏面的綁定函數的超時時間如下

$(window).bind('orientationchange', function(e){ 
    setTimeout(function() { 
     var device_width = $(window).width(); 
    },500); 
    }); 

在這裏閱讀更多:Device and Viewport Size In JavaScript

對於

  • 如何獲得視區大小
  • 如何獲得設備的尺寸。
  • 如何獲取文檔大小。

還可以閱讀:http://www.w3schools.com/js/js_window_screen.asp

+0

謝謝!在第一篇文章中觀看我的解決方案。 – simonhard