【问题标题】:(Chromium) alpha color value (in rgba) in CSS and javascriptCSS 和 javascript 中的 (Chromium) alpha 颜色值(以 rgba 为单位)
【发布时间】:2016-06-14 02:30:40
【问题描述】:

如果我在 javascript 中通过 rgba(r, g, b, a) 将 alpha 值设置为 1 以外的任何值,浏览器设置的实际值会略有不同。但是 CSS 中设置的值是完全匹配的。

查看代码示例 code-pen-site

    <head>    
      <script type="text/javascript" language="javascript">
        window.onload=function() {
        document.getElementById("p1").style["background-color"]="rgba(255,0,0,0.3)";
        }
      </script>
    </head>

    <body>
      <p>RGB colors with opacity:</p>
      <p id="p1">Red</p>
      <p id="p2">Green</p>
    </body>
  1. 使用 Chromium 浏览器
  2. 按 F12 激活 Inspector
  3. 检查“红色”。
  4. “红色”的背景颜色设置为 rgba(255,0,0,0.3),但在 Inspector 中其值为 rgba(255, 0, 0, 0.298039)
  5. “绿色”的背景颜色设置为 rgba(0,255,0,0.3),并且 Inspector 中的值与之匹配。

为什么如果 CSS 颜色是通过 Javascript 设置的,那么数字会改变?

【问题讨论】:

  • 当 chrome 用一个小数点定义时,它似乎将 +/- 0.001961 常量与 alpha 值相加。也有更多的小数,值再次改变。这似乎是一个错误

标签: javascript css chromium


【解决方案1】:

首先,我最初的观察是不正确的。如果您单击“Computed”选项卡来检查背景颜色,则会在“style”标签内的 CSS 规则和元素内的内联规则中观察到这种差异。我

chromium source code 这个实现解释了 alpha 值的 0.001961 差异

// Convert the floating pointer number of alpha to an integer in the range [0, 256),
// with an equal distribution across all 256 values.
int alphaComponent = 
    static_cast<int>(
        clampTo<double>(alpha, 0.0, 1.0) * nextafter(256.0, 0.0));

这里如果 alpha 为 0.3,则 alphaComponent 变为 0.298039。 (如果我将 alpha 设置为 [0.0, 1.0] 中的任何浮点数,webInspector 显示的数字与从上述公式获取的 alphaComponent 值匹配。

【讨论】:

    猜你喜欢
    • 2015-04-08
    • 2018-07-10
    • 2016-05-16
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多