How can I detect via JavaScript if browser supports CSS3 media queries and CSS3 gradient?

£可爱£侵袭症+ 提交于 2019-12-13 00:41:38

问题


How can I detect via JavaScript if browser supports CSS3 media queries?

How can I detect via JavaScript if browser supports CSS3 gradient?

Thank you.


回答1:


Have a look at http://modernizr.com/, it's a great library for featuredetection using javascript.




回答2:


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 (Modernizr is really awesome, but sometimes you just want a brick, not a house):

function mediaQueriesSupported()
{
    if(typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined")
    {
        // alert("media queries are supported!");
        return true;
    }else{
        // alert("no media query support :(");
        return false;
    }
}

Or more elegantly:

function mediaQueriesSupported()
{
    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

As for gradient support detection, there are some great answers here and here. Effectively you're just setting the property and then testing for it after the fact. Browsers will throw out junk or unsupported CSS properties.

EDIT:

Niet has an excellent answer to this problem over here, similar to my suggestions for gradient detection. It's not pure Javascript (it requires a very small amount of CSS) but it's an absolutely fool-proof method.




回答3:


check these links

+ How to detect if Media Queries are present using Modernizr

+ What’s New in Modernizr 2



来源:https://stackoverflow.com/questions/11807088/how-can-i-detect-via-javascript-if-browser-supports-css3-media-queries-and-css3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!