Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

css - I need an easy way to detect CSS3 media query support using jquery

I need a quick and dirty way to detect media query support using jquery. I defined a function as follows:

function mediaQueriesEnabled () {
   var v = parseFloat($.browser.version);
   if ($.browser.msie) {
      if (v < 9)
         return (false);
   }
   return (true);
}

Can someone help me fix this up a bit? Looking at this page:

http://caniuse.com/css-mediaqueries

I realized that there are some complexities here. For example, when I test my version of safari, I get "534.57.2". I want to avoid installing modernizr for now, mainly because I'm in a crunch and I need to handle most situations in the short term. Any help is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: I'm no longer curating this answer as I feel that Niet's is much better (see chosen answer). It should still work, but may need some testing.

Cracking open Modernizr (which can test for media queries) we see it uses the window.matchMedia (MDN page) function. We can check in plain old vanilla JS to see if this function exists:

function mediaQueriesEnabled () {
    if(typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined") {
        return true;
    } else {
        return false;
    }
}

Or more elegantly:

function mediaQueriesEnabled () {
    return (typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined");
}

JSFiddle

I've tested in the following browsers that support media queries, all correctly returned true:

  • Safari Mobile
  • Chrome 26

I've tested in the following browsers that do not support media queries, all correctly returned false:

  • IE 7

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...