如何比较 jQuery/JavaScript 中的两个颜色值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2377696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I compare two color values in jQuery/JavaScript?
提问by newbie
I get color value with jQuery with .css('color'), and then I know color that it should be.
我使用 jQuery 获得颜色值.css('color'),然后我知道它应该是什么颜色。
How can I compare color value that I get from jQuery with for example black color value?
如何比较从 jQuery 获得的颜色值与例如黑色值?
采纳答案by Andy Shellam
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 替换为要比较的颜色值的红色、绿色和蓝色值。
回答by Mike
Here is an approach that should work on all browsers using JQuery:
这是一种适用于所有使用 JQuery 的浏览器的方法:
- 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) - Set the color of the dummy element to the expected color, i.e.
$('#dummy').css('color','black'); - Compare the color of the dummy element with the element you want to check
<div id="dummy" style="display:none;"></div>在您的 HTML 页面上创建一个隐藏的 div 。(使用 JQuery 动态创建虚拟元素不适用于命名颜色)- 将虚拟元素的颜色设置为预期的颜色,即
$('#dummy').css('color','black'); - 将虚拟元素的颜色与要检查的元素进行比较
i.e.
IE
if($('#element').css('color') === $('#dummy').css('color')) {
//do something
}
回答by vjorjo
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
}
回答by Charlie Kilian
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 中测试。
回答by Daniel Doinov
Actually I tried Charlie Kilian'sanswer. For some reason it didn't work when you try to set .css('color')with and 'rgb(0,0,0)' value.
其实我试过查理基利安的答案。出于某种原因,当您尝试.css('color')使用 'rgb(0,0,0)' 值进行设置时,它不起作用。
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}
回答by oriadam
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 colorValuesfunction found here (gist)or here (SO answerwill always give you [r,g,b,a]array of numeric values.
Then you can compare them like this:
CSS 颜色可以以多种格式出现 - rgb、rgba、#hex、几乎不支持的#hexalpha、臭名昭著的命名颜色和特殊的transparent. 要将任何颜色与任何颜色进行比较,您需要先对它们进行标准化。在此处 (gist)或此处colorValues找到的函数(SO answer将始终为您提供数值数组。
然后您可以像这样比较它们:[r,g,b,a]
var sameColor = colorValues(color1).join(',') === colorValues(color2).join(',');
colorValues function
颜色值函数
// 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
});
}
}

