javascript - tricks to deal with colors

There are a couple of ways to represent a color information. and it always cause confusion across different browsers.

 

 

• rgb(R,G,B) - Where R, G, B are numbers from 0 to 255.

• rgb(R%,G%,B%) - Where R, G, B are numbers from 0% to 100%.

• #RRGGBB - Where RR, GG, BB are hexadecimal representations of the numbers 0 through 255.

• #RGB - Where R, G, B are hexadecimal representations similar to the previous one, but in shorthand

(e.g. #F54 is equal to #FF5544).

• red, blue, etc. - The name representing a set of RGB values.

 

the following code is from the jQuery and is written by jQuery's color plugin's author, I am showing it here to manifest just a reminder of the different of different colors. 

 

/**************************************
*@Name: expandoattr.js
*@Summary
*  this function shows hwo you can parse colors in different format to a single format.
*
*
***************************************/
var num = /rgb\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/,
    pc = /rgb\(\s*([0-9.]+)%\s*,\s*([0-9.]+)%\s*,\s*([0-9.]+)%\s*\)/,
    hex = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
    hex2 = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/;
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
  var result;
  // Look for rgb(num,num,num)
  if (result = num.exec(color))
    return [parseInt(result[1]), parseInt(result[2]),
parseInt(result[3])];

  // Look for rgb(num%,num%,num%)
  if (result = pc.exec(color))
    return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55,
parseFloat(result[3]) * 2.55];
  // Look for #a0b1c2
  if (result = hex.exec(color))
    return [parseInt(result[1], 16), parseInt(result[2], 16),
parseInt(result[3], 16)];
  // Look for #fff
  if (result = hex2.exec(color))
    return [parseInt(result[1] + result[1], 16),
parseInt(result[2] + result[2], 16),
parseInt(result[3] + result[3], 16)];
  // Otherwise, we're most likely dealing with a named color
  return colors[color.replace(/\s+/g, "").toLowerCase()];
}
// Map color names to RGB values
var colors = {
  aqua: [0, 255, 255],
  azure: [240, 255, 255],
  beige: [245, 245, 220],
  black: [0, 0, 0],
  blue: [0, 0, 255],
  // ... snip ...
  silver: [192, 192, 192],
  white: [255, 255, 255],
  yellow: [255, 255, 0]
};
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值