How can I detect CSS Variable support with JavaScript?

后端 未结 4 1304
梦毁少年i
梦毁少年i 2021-02-01 04:32

The latest version of Firefox has support for CSS Variables, but Chrome, IE and loads of other browsers do not. It should be possible to access a DOM Node or write a little meth

4条回答
  •  攒了一身酷
    2021-02-01 05:11

    I had problems getting the window.CSS.supports method to work for testing css variables in chrome 49 (even though it has native support). Ended up doing this:

    var supportsCssVars = function() {
        var s = document.createElement('style'),
            support;
    
        s.innerHTML = ":root { --tmp-var: bold; }";
        document.head.appendChild(s);
        support = !!(window.CSS && window.CSS.supports && window.CSS.supports('font-weight', 'var(--tmp-var)'));
        s.parentNode.removeChild(s);
        return support;
    }
    
    console.log("Supports css variables:", supportsCssVars());
    

    Seems to work in all browsers I tested. Probably the code can be optimised though.

提交回复
热议问题