2013-06-28 36 views
9

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

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

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

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

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

+1

你应该*不*使用客户端脚本这一点。你不能认为它是可用的或给你正确的值。让用户选择他们需要的东西。 – PointedEars

+0

我这样做是为了让用户更容易,如果不是,它会回退到默认分辨率。 – Banana

+0

只要你离开他们的选择是可以的。 – PointedEars

回答

28

您或许可以使用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; 
+0

这会返回两次较小的分辨率,360x640 :( – Banana

+0

@Mandarinica更新回答 – K3N

+1

太棒了,肯,这样做的工作:)非常感谢,一直在努力与此相当一段时间:) – Banana

0

您可以使用window.screen.widthwindow.screen.height检测的屏幕分辨率装置。

+0

这将返回两次较小的分辨率,360x640 :( – Banana

0

这将在美孚设备

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

肯费腾博格,伟大的东西,感谢工作。我一直在寻找一种简单的方法来检测所有可能的屏幕尺寸和分辨率数据,并回答这个比例的好处,它可以让您看到它是否是例如视网膜显示类型的高分辨率设备。

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

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

我能得到一个很好的实际画面感/触动我们的真正的用户正在运行的设备的规格。

对于网络的东西,当然,你真正感兴趣的是实际的浏览器内部窗口的大小,你分配在设备上的空间。就像旁人一样,我已经看到苹果设备似乎总是给人像模式尺寸,例如非视网膜显示iPad的768 x 1024,这有点烦人,因为我也希望能够学习大多数用户的实际情况与网站和我们的网站进行互动。

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; 

这就造成了很多关于客户端系统,你可以接着使用任何你喜欢的方法传递给一些数据。

UPDATE: 它只是把使用这种方法几分钟就找到苹果设备实际上是如何报告其宽度/高度:

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

正如你所看到的,document.documentElement.clientWidth方法,如果肖像报告的实际宽度/景观,好东西。