在移动网站上获取屏幕分辨率

时间:2013-06-28 07:56:17

标签: javascript mobile

我正在设计一个移动网站,其中有一个部分可以从中下载壁纸。为了容纳许多用户,我希望能够根据屏幕分辨率下载壁纸。我想从JavaScript中检测分辨率并显示适当的壁纸。

这是我在网上找到并尝试失败的xD:

width  = window.innerWidth  || document.body.clientWidth
height = window.innerHeight || document.body.clientHeight;

对于我的SGS3,其分辨率为720x1280,我得到了360x567。

我应该如何从JavaScript中发现手机的分辨率?

4 个答案:

答案 0 :(得分:31)

您也许可以使用screen对象:

var w = screen.width;
var h = screen.height;

更新 - 尝试将其与window.devicePixelRatio

一起使用
var ratio = window.devicePixelRatio || 1;
var w = screen.width * ratio;
var h = screen.height * ratio;

答案 1 :(得分:3)

Ken Fyrstenberg,很棒,谢谢。我正在寻找一种简单的方法来检测所有可能的屏幕尺寸和分辨率数据,并回答这个比例有什么用的问题,它可以让你看看它是否是例如视网膜显示型高分辨率设备

wh:768x1024 cwh:768x905 rwh:1536x2048 ts:touch

结合触摸测试检查此相关SO

我可以很好地了解真实用户正在运行的设备的实际屏幕/触摸规格。

对于Web内容,当然,您真正感兴趣的是实际浏览器内部窗口的大小,即您在设备上分配的空间。另外,我已经看到苹果设备似乎总是给出肖像模式尺寸,例如768 x 1024用于非视网膜显示器iPad,这有点烦人,因为我希望也学习如何用户实际上与网站和我们的网站进行互动。

Android似乎给出了该时刻的实际宽度/高度,即横向或纵向宽度/高度。

例如:

var ratio = window.devicePixelRatio || 1;
var is_touch_device = 'ontouchstart' in document.documentElement;
var touch_status = (is_touch_device) ? 'touch' : 'no-touch';
touch_status = ' ts:' + touch_status;
var width_height = 'wh:' + screen.width + 'x' + screen.height;
var client_width_height = ' cwh:' + document.documentElement.clientWidth + 'x' + document.documentElement.clientHeight;
var rw = screen.width * ratio;
var rh = screen.height * ratio;
var ratio_width_height = ' r:' + ratio + ' rwh:' + rw + 'x' + rh;
var data_string = width_height + client_width_height + ratio_width_height + touch_status;

这会创建大量有关客户端系统的数据,然后您可以使用您喜欢的任何方法将其传递给某些内容。

更新: 使用此方法只花了几分钟来查找苹果设备实际报告其宽度/高度的方式:

wh:375x667 cwh:667x375 r:2 rwh:750x1334 ts:touch Device type: mobile

正如您所看到的,document.documentElement.clientWidth方法报告了纵向/横向的实际宽度,这是好东西。

答案 2 :(得分:2)

这也适用于移动设备

screen_width = document.documentElement.clientWidth;
screen_heght = document.documentElement.clientHeight;

答案 3 :(得分:0)

您可以使用window.screen.widthwindow.screen.height来检测设备的屏幕分辨率。