请考虑以下代码段:
var el = document.getElementById('x');
el.style.backgroundColor = "rgba(124, 181, 236, 0.25)";
alert(el.style.backgroundColor);

<div id="x">Testing</div>
&#13;
在Windows 8.1上,这会在IE 11和Firefox 37中返回backgroundColor
的确切输入,但在Chrome 43中,它会更改alpha值,并且警报显示:
rgba(124,181,236,0.247059)
请注意,alpha值意外返回0.247059
而不是0.25
。
我已经完成了the background-color
spec以及the rgba spec,更具体地说the bit about alpha values,但未能确定这是一个错误还是UA(在这种情况下是Chrome) )被允许这样做。
是否有任何相关规范说明Chrome的行为是否被允许&#34;?作为奖励,任何人都可以解释为什么 Chrome会巧妙地改变alpha值?
脚注:检查是否是&#34; setter&#34; (el.style.backgroundColor = ...
)应该归咎于我还尝试在DOM内部的元素上声明样式。这将具有相同(意外)的结果。请参阅以下代码段:
document.addEventListener("DOMContentLoaded", function(event) {
var el = document.getElementById('x');
alert(el.style.backgroundColor);
});
&#13;
<div id="x" style="background-color: rgba(124, 181, 236, 0.25);">Testing</div>
&#13;
答案 0 :(得分:4)
这是Chrome的一个已知问题,很长一段时间......
这是由于Chrome如何计算计算出的样式 alpha值。
例如,输入的alpha值为0.25
。
0.25 * 255 = 63.75
。63
。63/255 = 0.24705882352941178
,大约0.247059
。不仅在使用JS设置颜色时,还会使用CSS。例如:
<style>
div { color: rgba(100, 100, 100, 0.3) }
<style>
<div></div>
<script>
document.querySelector('div').style.color // rgba(100, 100, 100, 0.298039)
</script>
答案 1 :(得分:1)
一种思想,因为RGBA是以32位表示的。这意味着实际上没有8位alpha的精确 0.25 。因此0.247059是实际正确的外推值。 Chrome错了吗?或者它实际上是正确的吗?而其他浏览器为您提供的无效数字不是页面上呈现内容的真实表示?
然后你可以争辩说W3C标准并不完全正确,并且它应该只允许使用8位Alpha完全设计的值。但是这只是一个推荐,而不是法律... < / p>
以下是Chromium定制的webkit color.cpp代码的精简版本,该代码看起来正在进行颜色转换。但后来我不是铬专家 http://www.chromium.org/developers/how-tos/getting-around-the-chrome-source-code
#include <iostream>
using namespace std;
typedef unsigned RGBA32;
int colorFloatToRGBAByte(float f)
{
return std::max(0, std::min(static_cast<int>(lroundf(255.0f * f)), 255));
}
RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a)
{
cout << "Alpha: " << a;
return colorFloatToRGBAByte(a) << 24 | colorFloatToRGBAByte(r) << 16 | colorFloatToRGBAByte(g) << 8 | colorFloatToRGBAByte(b);
}
int main()
{
RGBA32 t;
t = makeRGBA32FromFloats (255.0f, 255.0f, 255.0f, 0.25f);
cout << static_cast<unsigned>(t) << std::endl;
return 0;
}