简体   繁体   中英

Media Queries in javascript

I was wondering how to write these values:

@media screen and (-webkit-min-device-pixel-ratio: 1.3), (min-resolution: 124.8dpi), (max-device-width: 550px)

So that I can write an if clause like so except with the values from above:

if (window.screenWidth >=550 || window.screenWidth >=550 ) {
}

I don't believe media queries like those are available as JS window properties, though there may be plugins out there that handle these queries.

One solution is to use the normal queries in CSS to style an arbitrary element a specific way that can simply be detected via javascript.

CSS:

@media screen and (-webkit-min-device-pixel-ratio: 1.3), (min-resolution: 124.8dpi), (max-device-width: 550px) {
    head { font-family: 'someValue'; }
}

JS (w/ jQuery):

$(function() {
    var foo = $('head').css('fontFamily').split("\"").join("").split("'").join(""); // split/joins needed for cross-browser compatibility
    if(foo === 'someValue') {
        doStuff();
    } else if(foo === 'someOtherValue') {
        doOtherStuff();
    }
}

Kind of a hack, but it works. I use a variation of that code for responsive designs.

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