getComputedStyle给出“透明”而不是实际的背景颜色 [英] getComputedStyle gives "transparent" instead of actual background color

查看:209
本文介绍了getComputedStyle给出“透明”而不是实际的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个惊喜。下面的代码似乎不能给我屏幕上的实际颜色:

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

给予 rgb 0,0,0)这是我认为是正确的。

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

window.getComputedStyle(h1).backgroundColor

给出 rgba(0,0,0,0)。我在屏幕上看到的实际背景颜色是白色。

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

我调用h1的元素在屏幕上可见。我期待得到实际的背景颜色。我得到的值(在rgba)没有错,但也不是非常有用。它只是告诉我背景是完全透明的 - 这不是一种颜色。

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.

如何获得RGB中的实际背景颜色?

How do I get the actual background color in RGB?

推荐答案

如果您设置背景颜色:rgba(255,255,255, 0 )你的css; getComputedStyle()将返回 transparent (在某些浏览器中),而不是您的rgba值。

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.

很容易解决这个问题是将alpha设置为高于0的值,例如
rgba(255,255,255, 0.01 );这将返回rgba(255,255,255, 0.01

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)

这篇关于getComputedStyle给出“透明”而不是实际的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆