如何比较jQuery / JavaScript中的两个颜色值?

时间:2021-05-02 12:05:54

I get color value with jQuery with .css('color'), and then I know color that it should be.

我使用带有.css('color')的jQuery获得颜色值,然后我知道它应该是颜色。

How can I compare color value that I get from jQuery with for example black color value?

如何比较从jQuery获得的颜色值,例如黑色值?

6 个解决方案

#1


14  

What about...

关于什么...

if ($('#element').css('color') == 'rgb(0, 0, 0)')
{
    // do something
}

Replace 0, 0, 0 with the red, green and blue values of the colour value you want to compare.

将0,0,0替换为要比较的颜色值的红色,绿色和蓝色值。

.css() jQuery API

.css()jQuery API

#2


21  

Here is an approach that should work on all browsers using JQuery:

这是一种适用于所有使用JQuery的浏览器的方法:

  1. Create a hidden div <div id="dummy" style="display:none;"></div> on your HTML page. (Creating the dummy element dynamically with JQuery does not work for named colors)
  2. 在HTML页面上创建一个隐藏的div
    。 (使用JQuery动态创建虚拟元素不适用于命名颜色)
  3. Set the color of the dummy element to the expected color, i.e. $('#dummy').css('color','black');
  4. 将虚拟元素的颜色设置为预期颜色,即$('#dummy')。css('color','black');
  5. Compare the color of the dummy element with the element you want to check
  6. 将虚拟元素的颜色与要检查的元素进行比较

i.e.

if($('#element').css('color') === $('#dummy').css('color')) {
  //do something
}

#3


5  

I had a similar problem where I had to toggle the bgnd color of an element. I solved it like this:

我有一个类似的问题,我不得不切换元素的bgnd颜色。我这样解决了:

var color_one = "#FFA500";
var color_two = "#FFFF00";

function toggle_color(elem){
    var bgcolor = elem.css("background-color");
    elem.css("background-color", color_one);     // try new color
    if(bgcolor == elem.css("background-color"))  // check if color changed
        elem.css("background-color", color_two); // if here means our color was color_one
}

#4


2  

Here is my implementation of Mike's answer, in one function.

以下是我在一个函数中实现Mike的答案。

function compareColors(left, right) {
    // Create a dummy element to assign colors to.
    var dummy = $('<div/>');

    // Set the color to the left color value, and read it back.
    $(dummy).css('color', left);
    var adjustedLeft = $(dummy).css('color');

    // Set the color to the right color value, and read it back.
    $(dummy).css('color', right);
    var adjustedRight = $(dummy).css('color');

    // Both colors are now adjusted to use the browser's internal format,
    // so we can compare them directly.
    return adjustedLeft == adjustedRight;
}

You don't need to actually add the elements to the DOM for this to work. Tested in IE8, IE10, FF, Chrome, Safari.

您无需将元素实际添加到DOM中即可使用。在IE8,IE10,FF,Chrome,Safari中测试过。

#5


0  

Actually I tried Charlie Kilian's answer. For some reason it didn't work when you try to set .css('color') with and 'rgb(0,0,0)' value.

其实我试过查理基利安的答案。出于某种原因,当您尝试使用和'rgb(0,0,0)'值设置.css('color')时,它不起作用。

I don't know why. Worked perfectly in the console. Maybe it was because my comparing function is in a javascript object and its some kind of a context issue or a reference problem. Either way finally I got frustrated and wrote my own function that will compare two colors regardless of the formats and does not create any elements or rely on jQuery. The function takes both HEX and RGB values.

我不知道为什么。完美地在控制台中工作。也许是因为我的比较函数是在一个javascript对象及其某种上下文问题或引用问题。无论哪种方式最终我都感到沮丧并编写了我自己的函数,无论格式如何都会比较两种颜色,并且不会创建任何元素或依赖于jQuery。该函数采用HEX和RGB值。

It can probably be optimized but I really don't have the time right now. Hope this helps someone its pure javascript.

它可能会被优化,但我现在真的没有时间。希望这可以帮助某人纯粹的javascript。

var compareColors= function (left, right) {
       var l= parseColor(left);
        var r=parseColor(right);
        if(l !=null && r!=null){
           return l.r == r.r && l.g == r.g && l.b == r.b;
        }else{
            return false;
        }
        function parseColor(color){
           if(color.length==6 || color.length==7){
                //hex color
               return {
                    r:hexToR(color),
                    g:hexToG(color),
                    b:hexToB(color)
                }
            }else if(color.toLowerCase().indexOf('rgb')>-1){
              var arr
                var re = /\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\s*/gmi;
                var m;

                if ((m = re.exec(color)) !== null) {
                    if (m.index === re.lastIndex) {
                        re.lastIndex++;
                    }
                    // View your result using the m-variable.
                    // eg m[0] etc.
                    arr = m[0].split(',');
                    return {
                        r: parseInt(arr[0].trim()),
                        g: parseInt(arr[1].trim()),
                        b: parseInt(arr[2].trim())
                    }
                }else{
                  return null;
                }

            } else{
                return null;
            }
            function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
            function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
            function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
            function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
        }
    }

These following functions I took from www.javascripter.net

我从www.javascripter.net上获得了以下这些功能

            function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
            function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
            function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
            function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

#6


0  

CSS Colors can appear in many formats - rgb, rgba, #hex, hardly supported #hexalpha, infamous named colors, and the special transparent. To compare any color to any color you need to normalize them first. The colorValues function found here (gist) or here (SO answer will always give you [r,g,b,a] array of numeric values.
Then you can compare them like this:

CSS颜色可以以多种格式出现 - rgb,rgba,#hex,几乎不支持#hexalpha,臭名昭着的命名颜色和特殊透明。要将任何颜色与任何颜色进行比较,首先需要将它们标准化。这里找到的c​​olorValues函数(gist)或这里(SO答案将总是给你[r,g,b,a]数值的数组。然后你可以像这样比较它们:

var sameColor = colorValues(color1).join(',') === colorValues(color2).join(',');

colorValues function

colorValues功能

// return array of [r,g,b,a] from any valid color. if failed returns undefined
function colorValues(color)
{
    if (color === '')
        return;
    if (color.toLowerCase() === 'transparent')
        return [0, 0, 0, 0];
    if (color[0] === '#')
    {
        if (color.length < 7)
        {
            // convert #RGB and #RGBA to #RRGGBB and #RRGGBBAA
            color = '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3] + (color.length > 4 ? color[4] + color[4] : '');
        }
        return [parseInt(color.substr(1, 2), 16),
            parseInt(color.substr(3, 2), 16),
            parseInt(color.substr(5, 2), 16),
            color.length > 7 ? parseInt(color.substr(7, 2), 16)/255 : 1];
    }
    if (color.indexOf('rgb') === -1)
    {
        // convert named colors
        var temp_elem = document.body.appendChild(document.createElement('fictum')); // intentionally use unknown tag to lower chances of css rule override with !important
        var flag = 'rgb(1, 2, 3)'; // this flag tested on chrome 59, ff 53, ie9, ie10, ie11, edge 14
        temp_elem.style.color = flag;
        if (temp_elem.style.color !== flag)
            return; // color set failed - some monstrous css rule is probably taking over the color of our object
        temp_elem.style.color = color;
        if (temp_elem.style.color === flag || temp_elem.style.color === '')
            return; // color parse failed
        color = getComputedStyle(temp_elem).color;
        document.body.removeChild(temp_elem);
    }
    if (color.indexOf('rgb') === 0)
    {
        if (color.indexOf('rgba') === -1)
            color += ',1'; // convert 'rgb(R,G,B)' to 'rgb(R,G,B)A' which looks awful but will pass the regxep below
        return color.match(/[\.\d]+/g).map(function (a)
        {
            return +a
        });
    }
}

#1


14  

What about...

关于什么...

if ($('#element').css('color') == 'rgb(0, 0, 0)')
{
    // do something
}

Replace 0, 0, 0 with the red, green and blue values of the colour value you want to compare.

将0,0,0替换为要比较的颜色值的红色,绿色和蓝色值。

.css() jQuery API

.css()jQuery API

#2


21  

Here is an approach that should work on all browsers using JQuery:

这是一种适用于所有使用JQuery的浏览器的方法:

  1. Create a hidden div <div id="dummy" style="display:none;"></div> on your HTML page. (Creating the dummy element dynamically with JQuery does not work for named colors)
  2. 在HTML页面上创建一个隐藏的div
    。 (使用JQuery动态创建虚拟元素不适用于命名颜色)
  3. Set the color of the dummy element to the expected color, i.e. $('#dummy').css('color','black');
  4. 将虚拟元素的颜色设置为预期颜色,即$('#dummy')。css('color','black');
  5. Compare the color of the dummy element with the element you want to check
  6. 将虚拟元素的颜色与要检查的元素进行比较

i.e.

if($('#element').css('color') === $('#dummy').css('color')) {
  //do something
}

#3


5  

I had a similar problem where I had to toggle the bgnd color of an element. I solved it like this:

我有一个类似的问题,我不得不切换元素的bgnd颜色。我这样解决了:

var color_one = "#FFA500";
var color_two = "#FFFF00";

function toggle_color(elem){
    var bgcolor = elem.css("background-color");
    elem.css("background-color", color_one);     // try new color
    if(bgcolor == elem.css("background-color"))  // check if color changed
        elem.css("background-color", color_two); // if here means our color was color_one
}

#4


2  

Here is my implementation of Mike's answer, in one function.

以下是我在一个函数中实现Mike的答案。

function compareColors(left, right) {
    // Create a dummy element to assign colors to.
    var dummy = $('<div/>');

    // Set the color to the left color value, and read it back.
    $(dummy).css('color', left);
    var adjustedLeft = $(dummy).css('color');

    // Set the color to the right color value, and read it back.
    $(dummy).css('color', right);
    var adjustedRight = $(dummy).css('color');

    // Both colors are now adjusted to use the browser's internal format,
    // so we can compare them directly.
    return adjustedLeft == adjustedRight;
}

You don't need to actually add the elements to the DOM for this to work. Tested in IE8, IE10, FF, Chrome, Safari.

您无需将元素实际添加到DOM中即可使用。在IE8,IE10,FF,Chrome,Safari中测试过。

#5


0  

Actually I tried Charlie Kilian's answer. For some reason it didn't work when you try to set .css('color') with and 'rgb(0,0,0)' value.

其实我试过查理基利安的答案。出于某种原因,当您尝试使用和'rgb(0,0,0)'值设置.css('color')时,它不起作用。

I don't know why. Worked perfectly in the console. Maybe it was because my comparing function is in a javascript object and its some kind of a context issue or a reference problem. Either way finally I got frustrated and wrote my own function that will compare two colors regardless of the formats and does not create any elements or rely on jQuery. The function takes both HEX and RGB values.

我不知道为什么。完美地在控制台中工作。也许是因为我的比较函数是在一个javascript对象及其某种上下文问题或引用问题。无论哪种方式最终我都感到沮丧并编写了我自己的函数,无论格式如何都会比较两种颜色,并且不会创建任何元素或依赖于jQuery。该函数采用HEX和RGB值。

It can probably be optimized but I really don't have the time right now. Hope this helps someone its pure javascript.

它可能会被优化,但我现在真的没有时间。希望这可以帮助某人纯粹的javascript。

var compareColors= function (left, right) {
       var l= parseColor(left);
        var r=parseColor(right);
        if(l !=null && r!=null){
           return l.r == r.r && l.g == r.g && l.b == r.b;
        }else{
            return false;
        }
        function parseColor(color){
           if(color.length==6 || color.length==7){
                //hex color
               return {
                    r:hexToR(color),
                    g:hexToG(color),
                    b:hexToB(color)
                }
            }else if(color.toLowerCase().indexOf('rgb')>-1){
              var arr
                var re = /\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\s*/gmi;
                var m;

                if ((m = re.exec(color)) !== null) {
                    if (m.index === re.lastIndex) {
                        re.lastIndex++;
                    }
                    // View your result using the m-variable.
                    // eg m[0] etc.
                    arr = m[0].split(',');
                    return {
                        r: parseInt(arr[0].trim()),
                        g: parseInt(arr[1].trim()),
                        b: parseInt(arr[2].trim())
                    }
                }else{
                  return null;
                }

            } else{
                return null;
            }
            function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
            function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
            function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
            function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
        }
    }

These following functions I took from www.javascripter.net

我从www.javascripter.net上获得了以下这些功能

            function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
            function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
            function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
            function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

#6


0  

CSS Colors can appear in many formats - rgb, rgba, #hex, hardly supported #hexalpha, infamous named colors, and the special transparent. To compare any color to any color you need to normalize them first. The colorValues function found here (gist) or here (SO answer will always give you [r,g,b,a] array of numeric values.
Then you can compare them like this:

CSS颜色可以以多种格式出现 - rgb,rgba,#hex,几乎不支持#hexalpha,臭名昭着的命名颜色和特殊透明。要将任何颜色与任何颜色进行比较,首先需要将它们标准化。这里找到的c​​olorValues函数(gist)或这里(SO答案将总是给你[r,g,b,a]数值的数组。然后你可以像这样比较它们:

var sameColor = colorValues(color1).join(',') === colorValues(color2).join(',');

colorValues function

colorValues功能

// return array of [r,g,b,a] from any valid color. if failed returns undefined
function colorValues(color)
{
    if (color === '')
        return;
    if (color.toLowerCase() === 'transparent')
        return [0, 0, 0, 0];
    if (color[0] === '#')
    {
        if (color.length < 7)
        {
            // convert #RGB and #RGBA to #RRGGBB and #RRGGBBAA
            color = '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3] + (color.length > 4 ? color[4] + color[4] : '');
        }
        return [parseInt(color.substr(1, 2), 16),
            parseInt(color.substr(3, 2), 16),
            parseInt(color.substr(5, 2), 16),
            color.length > 7 ? parseInt(color.substr(7, 2), 16)/255 : 1];
    }
    if (color.indexOf('rgb') === -1)
    {
        // convert named colors
        var temp_elem = document.body.appendChild(document.createElement('fictum')); // intentionally use unknown tag to lower chances of css rule override with !important
        var flag = 'rgb(1, 2, 3)'; // this flag tested on chrome 59, ff 53, ie9, ie10, ie11, edge 14
        temp_elem.style.color = flag;
        if (temp_elem.style.color !== flag)
            return; // color set failed - some monstrous css rule is probably taking over the color of our object
        temp_elem.style.color = color;
        if (temp_elem.style.color === flag || temp_elem.style.color === '')
            return; // color parse failed
        color = getComputedStyle(temp_elem).color;
        document.body.removeChild(temp_elem);
    }
    if (color.indexOf('rgb') === 0)
    {
        if (color.indexOf('rgba') === -1)
            color += ',1'; // convert 'rgb(R,G,B)' to 'rgb(R,G,B)A' which looks awful but will pass the regxep below
        return color.match(/[\.\d]+/g).map(function (a)
        {
            return +a
        });
    }
}