Window.getcomputedstyle Not Working For Shorthand Properties In Other Browsers Except Chrome
Solution 1:
The shorthand property problem
background
is a shorthand property, a combination of background related properties. When you set a background of pink
, it is actually setting a number of background properties, just one of which is backgroundColor
. For instance, it is probably actually doing the equivalent of rgb(255, 165, 0) none repeat scroll 0% 0% / auto padding-box border-box
.
getComputedStyle
will not return the value of shorthand properties, except in Chrome as you've discovered.
To get the computed style, look for the value of primitive properties such as backgroundColor
, not that of shorthand properties such as background
.
A different approach?
However, this is not really how you want to be doing things. Instead of setting styles on your elements directly, you're going to find your code to be much cleaner if you add and remove classes from your elements, and then define the rules for the classes. As you've found, setting styles directly on elements may require you to then go back and query the style, whereas with classes, you can easily query the existing class with elt.classList.has()
, or toggle with .toggle()
, or add, or remove.
More on getComputedStyle
getComputedStyle
is a rather specialized API that should only be necessary in special situations.
For more on the issue of getComputedStyle
and shorthand properties, see this question. A bug was reported against FF and you can find it here.
See this MDN page. It says that CSSStyleDeclaration
(which is what is returned by getComputedStyle
) has a getPropertyCSSValue
method which
returns ... null for Shorthand properties.
Post a Comment for "Window.getcomputedstyle Not Working For Shorthand Properties In Other Browsers Except Chrome"