我想在客户端 JavaScript 代码中按屏幕宽度对设备进行分类
所有适合一只手(小于 7 英寸)的设备均属于移动类别
将其他设备视为桌面设备
回退:将不支持必要 API 的设备视为移动设备
问题
- 我可以使用哪些相关的 JavaScript 和 CSS API 来检测屏幕的物理尺寸?请注意,这些 API 不必在旧版浏览器中得到支持,因为存在安全回退。此外,我也不关心旧版桌面浏览器。
Firefox 支持是可选的 - 如果它们已经有兼容的 API。
请注意,这是关于物理尺寸,而不是像素尺寸。
最佳答案
有 no direct way以英寸为单位获取屏幕尺寸,但有一些变通方法使用屏幕密度来查找设备尺寸。它并不完美,但您真的不需要知道 5 位有效数字的确切大小。此外,IMO 通常最好只使用像素值。
HTML
制作一个测试 div,然后查看显示的像素数以获得像素密度,然后将其用于您的计算。这应该有效,假设您的浏览器/操作系统配置正确(它在 this question 中不起作用,但在我的计算机上它在半英寸以内)。
编辑:这是 100% 错误的。 CSS 中的英寸/厘米测量值并非基于实际的物理测量值。它们基于精确的转换(1 英寸 = 96 像素,1 厘米 = 37.8 像素)。抱歉。
CSS
检测物理屏幕尺寸的最佳方法是使用 CSS 媒体查询。 min-resolution
和 max-resolution
查询可用于获取 dpi
或 dpcm
中的分辨率:
@media (min-resolution: 300dpi){
// styles
}
将它与 min-device-width
和 max-device-width
查询结合起来,你会得到如下内容:
@media (resolution: 326dpi) and (device-width: 640) and (device-height: 960){
// iPhone
}
问题是,如果你想定位 7 英寸设备,你必须同时拥有许多分辨率和相应的宽度,这可能会变得很复杂。
更多信息:
- MDN- CSS Media Queries
- MDN- Resolution
- "Mobifying" Guide
- High DPI Images for Variable Pixel Densities (有点相关)
Javascript
您可以使用 window.devicePixelRatio
来确定屏幕密度。来自 Android's WebView Reference :
The
window.devicePixelRatio
DOM property. The value of this property specifies the default scaling factor used for the current device. For example, if the value ofwindow.devicePixelRatio
is "1.0", then the device is considered a medium density (mdpi) device and default scaling is not applied to the web page; if the value is "1.5", then the device is considered a high density device (hdpi) and the page content is scaled 1.5x; if the value is "0.75", then the device is considered a low density device (ldpi) and the content is scaled 0.75x.
然后使用它,您可以通过将其除以总像素数来计算物理尺寸,这可以通过 window.screen.width
和 window.screen.height
来计算code>(不要使用 window.screen.availHeight
或 window.screen.availWidth
,因为它们仅检测可用高度)。
更多信息:
关于javascript - 在 JavaScript 中检测 WebKit 设备的物理屏幕尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16141545/