在javascript中获取设备宽度 [英] Get the device width in javascript

查看:229
本文介绍了在javascript中获取设备宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用javascript来获取用户设备宽度,而不是视口宽度?



CSS媒体查询,我可以说

  @media屏幕和(max-width:640px){
/ * ... * /
}

  @media screen and(max-device-width:960px){
/ * ... * /
}

如果我将横向定位智能手机,这将非常有用。例如,在iOS上, max-width:640px 的声明将同时定位横向和纵向模式,即使在iPhone 4上也是如此。因此,在这种情况下,使用device-width可以成功定位到两个方向,而无需定位到桌面设备。



根据设备宽度调用javascript绑定,我似乎限于测试视口宽度,这意味着一个额外的测试,如下所示:

  if($(window).width()< = 960&& $(window).height< = 640){/ * ... * /} 



这看起来并不优雅,给出了设备宽度可用于css的提示。


您可以通过screen.width属性获取设备屏幕宽度。
$
有时候,使用window.innerWidth(非常有用)通常在移动设备上找到)而不是屏幕宽度。



通常,当处理移动设备时和桌面浏览器我使用以下:

  var width =(window.innerWidth> 0)? window.innerWidth:screen.width; 


Is there a way to get the users device width, as opposed to viewport width, using javascript?

CSS media queries offer this, as I can say

@media screen and (max-width:640px) {
    /* ... */
}

and

@media screen and (max-device-width:960px) {
    /* ... */
}

This is useful if I'm targeting smartphones in landscape orientation. For example, on iOS a declaration of max-width:640px will target both landscape and portrait modes, even on an iPhone 4. This is not the case for Android, as far as I can tell, so using device-width in this instance successfully targets both orientations, without targeting desktop devices.

However, if I'm invoking a javascript binding based on device width, I appear to be limited to testing the viewport width, which means an extra test as in the following,

if ($(window).width() <= 960 && $(window).height <= 640) { /* ... */ }

This doesn't seem elegant to me, given the hint that device width is available to css.

解决方案

You can get the device screen width via the screen.width property.
Sometimes it's also useful to use window.innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.

Typically, when dealing with mobile devices AND desktop browsers I use the following:

 var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

这篇关于在javascript中获取设备宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆