window.getComputedStyle not working for shorthand properties in other browsers except Chrome

断了今生、忘了曾经 提交于 2019-11-29 07:09:31

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!