How can I detect via JavaScript if browser support

2019-08-03 09:46发布

问题:

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