getComputedStyle gives “transparent” instead of actual background color

寵の児 提交于 2019-12-06 01:15:33

问题


This was a surprise. The following code does not seem to give me the actual colors on the screen:

h1 = document.querySelector("h1");
window.getComputedStyle(h1).color

Gives rgb(0, 0, 0) which I think is correct. However

window.getComputedStyle(h1).backgroundColor

gives rgba(0, 0, 0, 0). The actual background color I see on the screen is white.

The element I call h1 is visible on the screen. I was expecting to get the actual background color. The value I get above (in rgba) is not wrong, but not very useful either. It just tells me the background is fully transparent - and that is not a color.

How do I get the actual background color in RGB?


回答1:


If you set your background-color: rgba(255, 255, 255, 0) in your css; getComputedStyle() will return transparent (in some browsers) instead of your rgba value.

Easy fix for this is setting alpha to something higher than 0 for example rgba(255, 255, 255, 0.01); This will return rgba(255, 255, 255, 0.01)




回答2:


getComputedStyle(h1) provides the css value of element after applied in active stylesheet.

Which means you can get those css value only which applied to particular element in any way.

Eg:- if you applied background for h1 :RGB{255, 255, 255}, then you will get the background color white in rgb format otherwise not. It does not provide value for html's default style.

To get the value by getComputedStyle(), First you should apply this to element.

For more info getComputedStyle()



来源:https://stackoverflow.com/questions/22876295/getcomputedstyle-gives-transparent-instead-of-actual-background-color

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