【问题标题】:How do I get the 'css-pixel' (media-query) width using Javascript?如何使用 Javascript 获取“css-pixel”(媒体查询)宽度?
【发布时间】:2016-02-28 03:20:38
【问题描述】:

我知道在获取设备尺寸等方面曾有人问过类似的问题,但对于解决此问题的确切方法似乎存在分歧。

假设我有媒体查询(例如 Twitter Bootstrap)

超小型设备电话 (

小型设备平板电脑(≥768px)

中型设备台式机(≥992px)

大型设备桌面(≥1200px)

现在,我希望能够使用 Javascript 来获得相同的输出。换句话说,css media-query 的像素数而不是实际的屏幕点数。即,我不需要得到确切的答案,但我想避免被排除在 2 或 3 倍之外,因为我得到的是“屏幕点”而不是 css 像素。

比起桌面设备,我更关心移动设备(尤其是 Android)。 screen.width 可靠吗?还是jQuery(document).width()

(这是一个研究项目,虽然我知道检测平板电脑和手机基本上是不可能的,但我想知道人们正在使用的设备的大小。用户体验不会受到影响结果。)

【问题讨论】:

标签: javascript android jquery css


【解决方案1】:

这是我经常使用的脚本:

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

然后您可以将其调用到一个变量中,并读取其高度和宽度属性:

var vp = viewport();
var vpWidth = vp.width;
var vpHeight = vp.height;

【讨论】:

    【解决方案2】:

    您可以像这样使用 Javascript 获取窗口宽度

    var wid = window.innerWidth;
    

    超小型设备电话 (

    if (wid < 767) {
       //execute this
    }
    

    小型设备平板电脑(≥768px)

    if (wid >= 768 && wid <= 991) {
       //execute this
    }
    

    中型设备台式机(≥992px)

    if (wid >= 992 && wid <= 1199) {
       //execute this
    }
    

    大型设备桌面(≥1200px)

    if (wid >= 1200) {
       //execute this
    }
    

    【讨论】:

      【解决方案3】:

      我最喜欢的方法如下(jQuery):

      var viewportWidth = $(window).width();
      // Then  create if statements and execute code accordingly... 
      if (viewportWidth <= 767) {
                 // execute code
      } else if (viewportWidth >= 768) {
                 // execute this
      }
      

      你也可以为宽度之间的视口执行代码,例如:

      if (viewportWidth >= 768 && viewportWidth <= 991) {
         //execute this
      }
      

      这将在视口介于 768px 和 991px 之间时执行代码...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-19
        • 2017-07-29
        • 2012-08-31
        • 1970-01-01
        • 1970-01-01
        • 2012-07-03
        • 1970-01-01
        相关资源
        最近更新 更多