请考虑以下代码段:
var el = document.getElementById('x');
el.style.backgroundColor = "rgba(124, 181, 236, 0.25)";
alert(el.style.backgroundColor);
<div id="x">Testing</div>
在 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 的行为是否“允许”?作为奖励,谁能解释为什么 Chrome 会巧妙地改变 alpha 值?
脚注:检查它是否是“setter”(el.style.backgroundColor = ...
)是罪魁祸首我也尝试过在 DOM 本身内的元素上声明样式.这将产生相同的(意外的)结果。看到这个片段:
document.addEventListener("DOMContentLoaded", function(event) {
var el = document.getElementById('x');
alert(el.style.backgroundColor);
});
<div id="x" style="background-color: rgba(124, 181, 236, 0.25);">Testing</div>
最佳答案
It's a known issue of Chrome, for quite a long time...
这取决于 Chrome 计算计算样式 alpha 值的方式。
例如,您输入的 alpha 值为 0.25
。
- Chrome 首先将其转换为 8bit 级别,
0.25 * 255 = 63.75
。 - 奇怪的是,这个数字被截断为一个整数,
63
。 - 然后,Chrome 使用整数返回 CSS3 颜色表示法,
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>
关于css - Chrome 在设置后稍微改变了 RGBA 颜色的 alpha 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30479757/