【问题标题】:Parse CSS Color to RGBA values将 CSS 颜色解析为 RGBA 值
【发布时间】:2016-05-16 08:45:57
【问题描述】:

我想从一些 CSS 数据类型值中获取 RGBA 值。

该函数应该接受一个描述某种颜色的字符串,并返回一个具有红色、绿色、蓝色和 alpha 值的对象。

例如:

parseColor('red') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('#f00') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('rgb(255,0,0)') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('hsla(0,100%,50%,0.1)') -> { red: 255, green: 0, blue: 0, alpha: 0.1 }
parseColor('transparent') -> { red: any_is_ok, green: any_is_ok, blue: any_is_ok, alpha: 0 }

所以,我尝试了这样的代码:

function parseColor(color) {
  var x = document.createElement('div');
  document.body.appendChild(x);
  var color, rgba;
  var red = 0, green = 0, blue = 0, alpha = 0;
  try {
    x.style = 'color: ' + color + '!important';
    color = window.getComputedStyle(x).color
    rgba = color.match(/rgba?\((.*)\)/)[1].split(',').map(Number);
    red = rgba[0];
    green = rgba[1];
    blue = rgba[2];
    alpha = '3' in rgba ? rgba[3] : 1;
  } catch (e) {
  }
  x.parentNode.removeChild(x);
  return {'red': red, 'green': green, 'blue': blue, 'alpha': alpha};
}

它适用于 Firefox、IE 和 Chrome。 但我想知道window.getComputedStyle(x).color 会返回什么? 此函数会总是rgb()rgba() 格式返回颜色吗? 规范是怎么说的?

还有,还有其他方法可以实现parseColor 函数吗?

【问题讨论】:

标签: javascript colors


【解决方案1】:

parseColor 函数通过创建虚拟元素并为其设置颜色来工作。因此它可以在 rgba() 或 rgb() 中获取颜色(这取决于color 是什么参数) 但结果将始终在 rgba() 中,因为

alpha = '3' in rgba ? rgba[3] : 1;

这意味着如果没有 alpha(a),它将设置为 1

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 2021-04-23
    • 2015-04-08
    • 2011-01-04
    • 2012-07-07
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多