如何通过CSS通过Javascript获取确切的RGBa值集? [英] How to get the exact RGBa value set through CSS via Javascript?
问题描述
在大多数浏览器我试过,一旦浏览器解析CSS,RGBa值似乎改变。
In most browsers I've tried, RGBa values seem to be changed once the browser parse CSS.
例如,以下CSS:
background-color: rgba(255, 0, 0, 0.5);
通过jQuery.css('background-color')或本地CSSStyleDeclaration .getPropertyValue('background-color'):
Gives the following CSS value when accessed via jQuery.css('background-color') or native CSSStyleDeclaration.getPropertyValue('background-color'):
rgba(255, 0, 0, 0.498039)
这里有一个小小的更多示例: http ://jsfiddle.net/hgFEj/3/
Here's a fiddle with more examples: http://jsfiddle.net/hgFEj/3/
Chrome和Safari会提供不同的结果。 Firefox似乎是唯一报告输入的确切值的浏览器。这是一个错误还是设计?
Chrome and Safari give different results. Firefox seems to be the only browser that reports the exact value as entered. Is this a bug or by design?
推荐答案
Mark Hubbart的注释是正确的。
Mark Hubbart's comment is correct.
32位颜色分为四个8位元件,每个元件的范围为0-255:红色,绿色,蓝色和 alpha 。我们将 alpha 或透明度表示为分数或百分比,因为它帮助我们十进制的人更快地想到它是多么透明。它实际上更好地被认为是不透明(好,不透明度),因为100%的透明度是0,而不是1。
32-bit color breaks down into four 8-bit components, each within the range 0-255: red, green, blue, and alpha. We express the alpha, or transparency, as a fraction or percentage since it helps us decimal-brained folks get a quicker idea of just how transparent it is. It is actually better thought of as opaqueness (well, opacity) since 100% transparent is 0, not 1.
现在,
Now, given 255 is the denominator for the alpha value, there is no way to express 0.5 exactly. The value you're seeing, 0.498039, comes from the nearest fraction, 127/255 (rounded to 6 decimal places). Safari returns 0.496094 which is 127/256 rounded to 6 decimal places, and to me seems a bug since that implies 257 values. I also doubt Firefox can accurately report 0.5 unless it is rounding to only 2 decimal places.
您可以通过创建一个jQuery插件在不同的浏览器中解决这个问题,on
You can work around this issue in different browsers by creating a jQuery plugin that, on first execution, checks to see what value is returned with a 50% alpha, and adjust all calculations accordingly.
parseFloat(
$('#divWith50PercentAlphaBackgroundStyle')
.css('background-color')
.split(',')[3],
10
)
然后,使用此值进行切换
对不同浏览器返回的值,并正确转换为您期望的最接近的正确值。
Then, with this value in hand, do a switch
on it against the values different browsers return, and properly convert to the closest correct value you're expecting.
这篇关于如何通过CSS通过Javascript获取确切的RGBa值集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!