[英]Add “width=device-width” in meta name=“viewport” if mobile phone
[英]How to programmatically find the device-width in Phonegap/JQuery mobile
我需要找到移動設備的設備寬度。 雖然我們可以指定內容
<meta name="viewport" content="width=device-width; user-scalable=no" />
但我需要以編程方式獲取設備寬度以在我的應用程序中計算一些邏輯。 如何獲得設備寬度?
可以通過window
對象收集viewport
尺寸:
var viewport = {
width : $(window).width(),
height : $(window).height()
};
//can access dimensions like this:
//viewport.height
雖然您不會總是得到完美的結果,但不同的設備表現不同,這給出了viewport
尺寸,而不是屏幕尺寸。
或者,您可以檢查data-role="page"
元素device-width
以查找device-width
(因為它設置為device-width
100%
):
var deviceWidth = 0;
$(window).bind('resize', function () {
deviceWidth = $('[data-role="page"]').first().width();
}).trigger('resize');
不確定提出的解決方案是否按預期工作。 你確定你獲得了真正的設備寬度嗎?
我在我的應用程序中使用以下代碼,它工作正常:
function effectiveDeviceWidth() {
var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height;
// iOS returns available pixels, Android returns pixels / pixel ratio
// http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html
if (navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio) {
deviceWidth = deviceWidth / window.devicePixelRatio;
}
return deviceWidth;
}
希望它可以幫助別人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.