简体   繁体   English

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

[英]How can I compare two color values in jQuery/JavaScript?

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 获得的颜色值与例如黑色值?

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

ie

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

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

I had a similar problem where I had to toggle the bgnd color of an element. 我有一个类似的问题,我不得不切换一个元素的bgnd颜色。 I solved it like this: 我这样解决了:

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
}

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. 您无需将元素实际添加到DOM中即可使用。 Tested in IE8, IE10, FF, Chrome, Safari. 在IE8,IE10,FF,Chrome,Safari中测试过。

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. 也许是因为我的比较函数是在一个javascript对象及其某种上下文问题或引用问题。 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. 无论哪种方式最终我都感到沮丧并编写了我自己的函数,无论格式如何都会比较两种颜色,并且不会创建任何元素或依赖于jQuery。 The function takes both HEX and RGB values. 该函数采用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}

CSS Colors can appear in many formats - rgb , rgba , #hex , hardly supported #hexalpha , infamous named colors, and the special transparent . CSS颜色可以以多种格式出现 - rgbrgba#hex ,几乎不支持#hexalpha ,臭名昭着的命名颜色和特殊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. 这里找到的colorValues函数(gist)这里(SO答案将始终为您提供[r,g,b,a]数值数组。
Then you can compare them like this: 然后你可以像这样比较它们:

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
        });
    }
}

Modified from Katie Kilian's but without requiring jQuery由 Katie Kilian 修改,但不需要 jQuery

<div id="dummy"></div>
function compareColors(left, right) {
    // Create a dummy element to assign colors to.
    document.getElementById('dummy').style.background = left;
    var adjustedLeft = document.getElementById('dummy').style.background;

    // Set the color to the right color value, and read it back.
    document.getElementById('dummy').style.background = right;
    var adjustedRight = document.getElementById('dummy').style.background;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM