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

Get screen resolution on a mobile website

本文关键字:获取 屏幕 分辨率 网站 移动 移动网      更新时间:2023-09-26

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

这是我在网上发现的,尝试并失败的xD:

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

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

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

您也许可以使用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;

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

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;

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

更新:使用这种方法只花了几分钟就可以发现苹果设备实际上是如何报告其宽度/高度的:

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

正如您所看到的,如果纵向/横向,document.documentElement.clientWidth方法会报告实际宽度,这很好。

这也适用于移动设备

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

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