简体   繁体   中英

How do I get the 'css-pixel' (media-query) width using Javascript?

I realize similar questions have been asked before regarding getting device sizes etc. but there seems to be disagreement about the exact way to go about this.

Suppose I have media-queries (eg Twitter Bootstrap) with

Extra small devices Phones (<768px)

Small devices Tablets (≥768px)

Medium devices Desktops (≥992px)

Large devices Desktops (≥1200px)

Now, I'd like to be able to use Javascript to essentially get the same output. In other words, the css media-query pixel number rather than the actual screen dots. ie I don't need to get the exact answer, but I want to avoid being out by a factor or 2 or 3 because I'm getting 'screen dots' rather than css pixels.

I'm more concerned with mobile devices - especially Android - than desktop. Is screen.width reliable for this? Or jQuery(document).width() ?

(This is for a research project and while I'm aware that it's basically impossible to detect tablet vs. phone, I'd like an indication of the size of the devices people are using. The user experience will not be dictated by the results.)

My favourite way of doing this is as follows (jQuery):

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

You can also execute code for viewports between widths, such as:

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

This would execute the code when the viewport is between 768px and 991px...

You can get window width using Javascript like this

var wid = window.innerWidth;

Extra small devices Phones (<768px)

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

Small devices Tablets (≥768px)

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

Medium devices Desktops (≥992px)

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

Large devices Desktops (≥1200px)

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

This is the script I always use:

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' ] };
}

You can then call it to a variable, and read its height and width properties:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM