Can I access the value of invalid/custom CSS properties from JavaScript?

后端 未结 3 1167
清酒与你
清酒与你 2020-11-27 20:10

Assume I have the following CSS:

div {
    -my-foo: 42;
}

Can I later in JavaScript somehow know what the value of the -my-foo

3条回答
  •  抹茶落季
    2020-11-27 20:45

    CSS Custom Properties

    DOM Level 2 style

    As pointed out by Anurag, this was something proposed in DOM Level 2 and later deprecated. Internet Explorer was the only browser that implemented it and they stopped supporting it in Edge. IE expects that the property doesn't start with a dash so my-foo: 42; should work.

    CSS variables style

    Newer browsers support CSS variables. These start with a double dash: --my-foo: 42; (they can be reused elsewhere like this font-size: var(--my-foo);)

    Example

    CSS

    div {
      --my-foo: 42;
      my-foo: 42;
    }
    

    JS

    // Chrome 49, Firefox 31, Safari 9.1 (future Edge):
    const cssVariable = bodyStyles.getPropertyValue('--my-foo')
    // IE:
    const cssCustomProperty = bodyStyles['my-foo']
    

    Browser Support

    Currently Microsoft Edge is the only browser with no support for either of these methods, but as of writing CSS variables in Edge are "under active development".

提交回复
热议问题