最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I establish the difference between two HEX colours? - Stack Overflow

programmeradmin1浏览0评论

I need to be able to extract the different between two hex colours, represented itself as a hex colour, in order to bine them at a later point using LESS.

Ideally, this would work in javascript

I need to be able to extract the different between two hex colours, represented itself as a hex colour, in order to bine them at a later point using LESS.

Ideally, this would work in javascript

Share Improve this question asked Mar 22, 2012 at 10:41 Mild FuzzMild Fuzz 30.9k34 gold badges105 silver badges152 bronze badges 4
  • 1 What do you mean when you say that you want to bine the colors? – Guffa Commented Mar 22, 2012 at 10:46
  • What have you tried? What exactly do you have problems with? Hexadecimal is just a number representation, so performing subtraction should not be the problem. – Felix Kling Commented Mar 22, 2012 at 10:47
  • It's not, though. It's three pairs. – Mild Fuzz Commented Mar 22, 2012 at 10:51
  • By bine, I mean add them together. Less allows you to do that. – Mild Fuzz Commented Mar 22, 2012 at 10:51
Add a ment  | 

2 Answers 2

Reset to default 8

If you want a full Javascript solution :

function parseHexColor(c) {
  var j = {};

  var s = c.replace(/^#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/, function(_, r, g, b) {
    j.red = parseInt(r, 16);
    j.green = parseInt(g, 16);
    j.blue = parseInt(b, 16);

    return "";
  });

  if(s.length == 0) {
    return j;
  }
};

function colorDifference(a, b) {
  var a = parseHexColor(a);
  var b = parseHexColor(b);

  if(typeof(a) != 'undefined' && typeof(b) != 'undefined') {
    return "#" + (a.red - b.red).toString(16) + (a.green - b.green).toString(16) + (a.blue - b.blue).toString(16);
  }
};

Try yourself :

colorDifference('#FFFFFF', '#AABBCC'); // returns : "#554433"

In LESS you can safely perform calculations on colors, so bining two is easy as this:

{
    color: #ff0000 + #00ff00;
}

or even

{
    color: red + green;
}

EDIT:

Similarly you are able to get the difference between two colors by mere subtracting them and storing the difference in a LESS variable for later.

@difference: #ffff00 - #ff0000;

should give you #00ff00 as a result.

发布评论

评论列表(0)

  1. 暂无评论