How can I detect CSS Variable support with JavaScript?

后端 未结 4 1298
梦毁少年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:15

    Set a CSS style with CSS variables and proof with Javascript and getComputedStyle() if it is set... getComputedStyle() is supported in many browsers: http://caniuse.com/#feat=getcomputedstyle

    HTML

    CSS

    :root {
      --main-bg-color: rgb(1, 2, 3); /* or something else */
    }
    
    .css-variable-test {
        display: none;
        background-color: var(--main-bg-color);
    }
    

    JavaScript

    var computedStyle = getComputedStyle(document.getElementsByClassName('css-variable-test')[0], null);
    
    if (computedStyle.backgroundColor == "rgb(1, 2, 3)") { // or something else
        alert('CSS variables support');
    }
    

    FIDDLE: http://jsfiddle.net/g0naedLh/6/

提交回复
热议问题